Since Xcode 8 and iOS10, views are not sized properly on viewDidLayoutSubviews

前端 未结 13 2218
北海茫月
北海茫月 2020-11-29 16:48

It seems that with Xcode 8, on viewDidLoad, all viewcontroller subviews have the same size of 1000x1000. Strange thing, but okay, viewDidLoad has n

13条回答
  •  情话喂你
    2020-11-29 17:25

    Better solution for me.

    protocol LayoutComplementProtocol {
        func didLayoutSubviews(with targetView_: UIView)
    }
    
    private class LayoutCaptureView: UIView {
        var targetView: UIView!
        var layoutComplements: [LayoutComplementProtocol] = []
    
        override func layoutSubviews() {
            super.layoutSubviews()
    
            for layoutComplement in self.layoutComplements {
                layoutComplement.didLayoutSubviews(with: self.targetView)
            }
        }
    }
    
    extension UIView {
        func add(layoutComplement layoutComplement_: LayoutComplementProtocol) {
            func findLayoutCapture() -> LayoutCaptureView {
                for subView in self.subviews {
                    if subView is LayoutCaptureView {
                        return subView as? LayoutCaptureView
                    }
                }
                let layoutCapture = LayoutCaptureView(frame: CGRect(x: -100, y: -100, width: 10, height: 10)) // not want to show, want to have size
                layoutCapture.targetView = self
                self.addSubview(layoutCapture)
                return layoutCapture
            }
    
            let layoutCapture = findLayoutCapture()
            layoutCapture.layoutComplements.append(layoutComplement_)
        }
    }
    

    Using

    class CircleShapeComplement: LayoutComplementProtocol {
        func didLayoutSubviews(with targetView_: UIView) {
            targetView_.layer.cornerRadius = targetView_.frame.size.height / 2
        }
    }
    
    myButton.add(layoutComplement: CircleShapeComplement())
    

提交回复
热议问题