Changing an Autolayout-constrained UIView's frame at runtime in Swift

萝らか妹 提交于 2020-01-02 07:02:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!