iOS auto layout's modification in custom view doesn't work until viewDidAppear gets called

Viewed 682

I've got view controller (using Storyboards if matters). Controller got custom view inside it let's call it AView. The view is laid out on storyboard as UIView object with custom class set. AView's contents are on separate XIB because I need this highly reusable. Here's how code looks like:

class VC: UIViewController {
    @IBOutlet weak var aView: AView!

    override func viewDidLoad() {
        super.viewDidLoad()
        aView.setup(false) //doesn't work
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        aView.setup(false) //doesn't work
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        aView.setup(false) //do work but glitches
    }

}

class AView: UIView {

    required init?(coder aDecoder: NSCoder) {
        //init stuff: loading nib, adding view from it
    }

    @IBOutlet weak var someView: UIView! //this view has all constraints which are required and additional rightConstraint which is inactive, for future use
    @IBOutlet var leftConstraint: NSLayoutConstraint!
    @IBOutlet var rightConstraint: NSLayoutConstraint!

    func setup(shouldBeOnLeft: Bool) {
        leftConstraint.active = true
        rightConstraint.active = false
        self.layoutIfNeeded()
    }
}

I need to setup this view before it appears, based on some parameters. I'm modifying only its internal content from inside. If I call aView.setup(shouldBeOnLeft:) in viewDidLoad or viewWillAppear constraints don't update or maybe do but I don't see changes. If I move it to viewDidAppear it works but obviously I see misplaced views for a while (state before setup).

The question is: how to get it work as intended and without view's manipulation form view controller and independent on how and where setup method is called unless it's inside or right after VC's viewDidLoad? Only thing that VC needs to know is to call setup with parameter.

2 Answers
Related