问题
For example, I use this code to change the frame position of a UIView
called Propo
:
self.Propo.frame.origin.x -= self.view.frame.width
(Propo
has constraints in Storyboard)
But When the app view disappears and reappears, the UIView
resets itself to its original position. How can I do to resolve it? I want the UIView
to keep its position when I change it programmatically.
I've tried updateViewConstraints()
by anything else append...
回答1:
Constraints and manual frame manipulation are directly in conflict. You have to choose one or the other. You should instead "promote" the constraint you wish to change by Ctrl-dragging it to your view controller as an @IBOutlet in Storyboard. Then, you can manipulate its constant:
class MyViewController: UIViewController {
@IBOutlet weak var myPropoLeftEdgeConstraint: NSLayoutConstraint!
@IBAction doChangePropo(sender: AnyObject) {
myPropoLeftEdgeConstraint.constant -= view.frame.width
view.layoutIfNeeded()
}
}
This is already covered in Objective C in many places, so just do a search on programmatically changing an NSLayoutConstraint in code if you can read those examples.
How to edit constraint in code
(Edit to make more applicable: generally constraints should be animated for a clean user experience. Otherwise the eye is confused.)
You can easily animate the constraint adjustment by wrapping view.layoutIfneeded
in a UIView.animateWithDuration(duration) { ... }
block.
来源:https://stackoverflow.com/questions/39193445/changing-an-autolayout-constrained-uiviews-frame-at-runtime-in-swift