iPhone UIView - Resize Frame to Fit Subviews

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

    Old question but you could also do this with a recursive function.

    You might want a solution that always works no matter how many subviews and subsubviews,...

    Update : Previous piece of code only had a getter function, now also a setter.

    extension UIView {
    
        func setCGRectUnionWithSubviews() {
            frame = getCGRectUnionWithNestedSubviews(subviews: subviews, frame: frame)
            fixPositionOfSubviews(subviews, frame: frame)
        }
    
        func getCGRectUnionWithSubviews() -> CGRect {
            return getCGRectUnionWithNestedSubviews(subviews: subviews, frame: frame)
        }
    
        private func getCGRectUnionWithNestedSubviews(subviews subviews_I: [UIView], frame frame_I: CGRect) -> CGRect {
    
            var rectUnion : CGRect = frame_I
            for subview in subviews_I {
                rectUnion = CGRectUnion(rectUnion, getCGRectUnionWithNestedSubviews(subviews: subview.subviews, frame: subview.frame))
            }
            return rectUnion
        }
    
        private func fixPositionOfSubviews(subviews: [UIView], frame frame_I: CGRect) {
    
            let frameFix : CGPoint = frame_I.origin
            for subview in subviews {
                subview.frame = CGRectOffset(subview.frame, -frameFix.x, -frameFix.y)
            }
        }
    }
    

提交回复
热议问题