Search code examples
iosswifttextviewconstraintsxcode-storyboard

Updating Main.storyboard constraints programatically (Swift)


I want to update the bottom anchor of my textview to a constant equal to the height of the keyboard when it appears so that it doesn't cover the text in the textView. I have a constraint identifier in Main.storyboard set as "bottomTextViewConstraint" for my textView, we well as the following code:

@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
                    print("This prints")
            for constraint in self.textView.constraints {
                    print("This does not print")
                if constraint.identifier == "bottomTextViewConstraint" {
                    constraint.constant = keyboardSize.height
                    print("This does not print")
                }
            }
            textView.updateConstraints()
        }
    }
}

self.textView.constraints is nil... It seems that programatically I can't access what I have set up in the storyboard. Any ideas why?


Solution

  • A constraint relating the bottom anchor of a text view and its super view's bottom anchor will be added to the text view's super view, so you cannot find it in textView.constraints.

    A much simpler way to do this is to add an IBOutlet from the storyboard:

    @IBOutlet var bottomConstraint: NSLayoutConstraint!
    

    Right click on your view controller in the storyboard, then connect bottomConstraint to the constraint shown in the outline view:

    enter image description here

    Then you can remove your entire for loop and replace it with just:

    bottomConstraint.constant = keyboardSize.height