iPhone UIView - Resize Frame to Fit Subviews

前端 未结 11 1537
时光取名叫无心
时光取名叫无心 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:35

    Updated @Mazyod's answer to Swift 3.0, worked like a charm!

    extension UIView {
    
    func resizeToFitSubviews() {
    
        let subviewsRect = subviews.reduce(CGRect.zero) {
            $0.union($1.frame)
        }
    
        let fix = subviewsRect.origin
        subviews.forEach {
            $0.frame.offsetBy(dx: -fix.x, dy: -fix.y)
            }
    
            frame.offsetBy(dx: fix.x, dy: fix.y)
            frame.size = subviewsRect.size
        }
    }
    

提交回复
热议问题