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
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.