Swift:显示键盘时更改自动布局约束

Man*_*tof 2 uitextview uikeyboard ios autolayout swift

UItextView当键盘出现时,我试图让变化约束的底部因此UItextView被textView"约束".我有一个在底部布局指南UIView之间命名的spacer UItextView.我试图将spacer的约束值更改为视图底部的键盘高度.任何帮助表示赞赏.

这是我的代码:

@IBOutlet weak var textView: UITextView!    
@IBOutlet weak var spacer: UIView!
@IBOutlet weak var spacerBottomLayoutConstraint: NSLayoutConstraint!
Run Code Online (Sandbox Code Playgroud)

viewDidLoad:

textView.becomeFirstResponder()

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AdditionalDetailsVC.keyboardShown(_:)), name: UIKeyboardDidShowNotification, object: nil)
Run Code Online (Sandbox Code Playgroud)

魔法发生的地方:

func keyboardShown(notification: NSNotification) {

    let info  = notification.userInfo!

    let value: AnyObject = info[UIKeyboardFrameEndUserInfoKey]!

    let rawFrame = value.CGRectValue

    keyboardFrame = view.convertRect(rawFrame, fromView: nil)

    print(keyboardFrame)

    print(spacerBottomLayoutConstraint)

    //Setting text field to bottom of keyboard
    //spacerBottomLayoutConstraint.constant = keyboardFrame.height

    UIView.animateWithDuration(1, animations: {

        self.spacerBottomLayoutConstraint.constant = self.keyboardFrame.height

        self.view.layoutIfNeeded()
    })
}
Run Code Online (Sandbox Code Playgroud)

mat*_*att 13

就个人而言,我发现调整文本视图的底部内容插入更加简单.此代码用于占据整个窗口的文本视图(因此其底部是屏幕的底部); 一个文档视图不会到目前为止需要更多的基本算术:

func keyboardShown(n:NSNotification) {
    let d = n.userInfo!
    var r = (d[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
    r = self.textView.convertRect(r, fromView:nil)
    self.textView.contentInset.bottom = r.size.height
    self.textView.scrollIndicatorInsets.bottom = r.size.height
}
Run Code Online (Sandbox Code Playgroud)