Xcode storyboard issue with auto layout not allowi

2019-04-15 09:02发布

问题:

In my storyboard I have just implemented size classes which added perfect constraints to my elements but when trying to modify where the elements y position is located to move it up on the keyboard show event so that it appears attached to the keyboard like this, the elements don't move at all because of the constraints. I have tried removing the constraints, which did not help. From what I've read my understanding of it is if there are no constraints, there are some generated when the app is built. How I used to programmatically move the elements can be seen here: i.imgur.com/uHfgEKl.png . I am asking how do I move the elements y position on the storyboard up with the size of the keyboard while size classes are enabled? If anyone knows how, please inform me. Sorry the last link is not hyperlinked, I have no reputation as I am new to stack overflow.

回答1:

Try this:

  1. Add a Vertical Space Constraint for your item and pin it a constant distance from the bottom of the screen. In Interface Builder, place your item near the bottom of the screen, select it, and then select the Auto Layout Pin icon |-[]-| and turn on the bottom strut. Set the constant to the initial value you want. Click Add 1 Constraint.

  2. Add an @IBOutlet to the constraint in your code.

    @IBOutlet weak var verticalSpaceConstraint: NSLayoutConstraint!
    

    You can do this by Control dragging from the constraint in the Document Layout View to your ViewController code.

  3. When you need to move your item, change constant

    // Move my item up 100 points
    verticalSpaceConstraint.constant += 100
    

If you want to animate the constraint change:

    self.view.layoutIfNeeded()
    verticalSpaceConstraint.constant += 100
    UIView.animateWithDuration(2.0) {
        self.view.layoutIfNeeded()
    }