Having trouble getting UIView sizeToFit to do anything meaningful

后端 未结 4 642
陌清茗
陌清茗 2020-12-09 02:07

When I add a subview to a UIView, or when I resize an existing subview, I would expect [view sizeToFit] and [view sizeThatFits] to ref

4条回答
  •  佛祖请我去吃肉
    2020-12-09 02:29

    If you won't override UIView, u can just use extension.

    Swift:

    extension UIView {
    
        func sizeToFitCustom () {
            var size = CGSize(width: 0, height: 0)
            for view in self.subviews {
                let frame = view.frame
                let newW = frame.origin.x + frame.width
                let newH = frame.origin.y + frame.height
                if newW > size.width {
                    size.width = newW
                }
                if newH > size.height {
                    size.height = newH
                }
            }
            self.frame.size = size
        }
    
    }
    

    The same code but 3 times faster:

    extension UIView {
        final func sizeToFitCustom() {
            var w: CGFloat = 0,
                h: CGFloat = 0
            for view in subviews {
                if view.frame.origin.x + view.frame.width > w { w = view.frame.origin.x + view.frame.width }
                if view.frame.origin.y + view.frame.height > h { h = view.frame.origin.y + view.frame.height }
            }
            frame.size = CGSize(width: w, height: h)
        }
    }
    

提交回复
热议问题