iPhone UIView - Resize Frame to Fit Subviews

前端 未结 11 1556
时光取名叫无心
时光取名叫无心 2020-12-04 17:51

Shouldn\'t there be a way to resize the frame of a UIView after you\'ve added subviews so that the frame is the size needed to enclose all the subviews? If your subviews are

11条回答
  •  情书的邮戳
    2020-12-04 18:14

    Although quite a few answers already, none worked for my use case. In case you use autoresizingMasks and want to resize view and move subviews so the size of rectangle matches subviews.

    public extension UIView {
    
        func resizeToFitSubviews() {
            var x = width
            var y = height
            var rect = CGRect.zero
            subviews.forEach { subview in
                rect = rect.union(subview.frame)
                x = subview.frame.x < x ? subview.frame.x : x
                y = subview.frame.y < y ? subview.frame.y : y
            }
            var masks = [UIView.AutoresizingMask]()
            subviews.forEach { (subview: UIView) in
                masks.add(subview.autoresizingMask)
                subview.autoresizingMask = []
                subview.frame = subview.frame.offsetBy(dx: -x, dy: -y)
            }
            rect.size.width -= x
            rect.size.height -= y
            frame.size = rect.size
            subviews.enumerated().forEach { index, subview in
                subview.autoresizingMask = masks[index]
            }
        }
    }
    

提交回复
热议问题