Opting out of auto layout for a single view?

前端 未结 3 1755
遇见更好的自我
遇见更好的自我 2021-02-19 06:37

I have a view that performs layout of its subviews in code. The layout is too complex for auto layout, and auto layout breaks the layout code. Is there any way to force auto l

相关标签:
3条回答
  • 2021-02-19 06:59

    Found the answer in the WWDC videos. layoutSubviews does not work the same under auto layout as it did before. It does not stop auto layout from happening, but rather is an opportunity to add/change/remove constraints during layout.

    Last night I tried moving the custom view to a different NIB and that seems to be the only solution.

    0 讨论(0)
  • 2021-02-19 07:04

    Auto-layout is enabled or disabled per storyboard or XIB. If your view is in its own XIB, then you can disable auto-layout for that XIB. If there are other views in your XIB that rely on auto-layout, you'll have to find a different solution.

    0 讨论(0)
  • 2021-02-19 07:07

    You can mix auto layout and manual layout!

    As long as none of a view's subviews are involved in any auto layout constraints that would trigger another auto layout pass on that view, you can override layoutSubviews and set the frame on each subview manually:

    class MyView : UIView {
    
        //
        // mySubview is not involved in any constraints 
        // that would trigger another layout pass.
        // e.g., no explicit constraints set in IB.
        // 
        @IBOutlet weak var mySubview: UIView!
    
        override func layoutSubviews() {
           super.layoutSubviews()  // let auto layout engine run first
    
           //
           // Auto layout engine now done with this view so we can
           // set the frames how ever we wish since we have the last
           // word! 
           //
           mySubview.frame  = CGRectMake(...)
           ...
    
        }
    
    }
    

    The reason this works is that after super.layoutSubviews() is called, changing the frames on any subviews does not trigger another layout pass (all constraints related to subviews are satisfied and the auto layout engine is done with them); therefore this method gets the last word on the position of its subviews!

    • Note that MyView instances can have related auto layout constraints set and everything works fine.

    • IB issues no warnings as long as you do not set any constraints on the subviews.

    0 讨论(0)
提交回复
热议问题