I have some constraints in the Interface Builder so when the view loads I'm removing all the constraints and adding new ones from code but they are messed up
here is my code(I know it's a bad styled code with flags etc, sorry for it, but the question is why it making the layout wrong):
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
self.view.layoutIfNeeded()
self.view.setNeedsUpdateConstraints()
self.view.layoutIfNeeded()
self.buttonsArray.forEach() { button in
NSLayoutConstraint(item: button, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: button, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: button, attribute: .Height, relatedBy: .Equal, toItem: self.view, attribute: .Height, multiplier: 0.15, constant: 0).active = true
}
}
var flagForOriginalConstraints = 0
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if flagForOriginalConstraints == 0 {
self.constraintsArray = self.view.constraints
self.flagForOriginalConstraints += 1
return
}
if flagForOriginalConstraints == 1 {
self.view.removeConstraints()
self.flagForOriginalConstraints += 1
return
}
}
remove the return here
if flagForOriginalConstraints == 0 {
self.constraintsArray = self.view.constraints
self.flagForOriginalConstraints += 1
return
}
seems like first time you are just incrementing flagForOriginalConstraints count and then the function returns
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.