Autolayout & programmatic constraints: How to deal with updateConstraints firing multiple times?

后端 未结 2 2001
太阳男子
太阳男子 2020-12-28 17:09

When programmatically creating layouts, I follow Apple\'s advice: override -updateConstraints, add custom constraints, and call -setNeedsUpdateConstraints once subviews have

相关标签:
2条回答
  • 2020-12-28 17:29

    Short answer: Potential solution number 2.

    Removing and reapplying all constraints may become costly as the layout becomes more complex. Besides, if your layout is stateful, you'd have more problems.

    Doubling constraints is very inefficient, you can never know how many times updateConstraints might be called.

    As this blog post shows, using a flag is the simplest, most efficient way of dealing with this problem. That is how I deal with it myself.

    As a side note, you mention of there existing an awesome way that you have not thought of yet. Most of the times, the simplest way IS the most awesome way. :)

    0 讨论(0)
  • 2020-12-28 17:39

    This kind of tracking could be done too, for the initial setup. In most cases.

    override func updateConstraints() {
                if constraints.count == 0 {
                    let views = ["textField": textField]
                    addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[textField]-0-|", options: [], metrics: nil, views: views))
                    addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[textField]-0-|", options: [], metrics: nil, views: views))
                }
                super.updateConstraints()
            }
    
    0 讨论(0)
提交回复
热议问题