2017-11-07 9 views
0

キーボード上にテキストフィールドが表示されたら移動する必要があります。スウィフト - 表示時にキーボード上でテキストフィールドを移動

override func viewDidLoad() { 
    super.viewDidLoad() 
NotificationCenter.default.addObserver(self, selector: #selector(self.keyBoardWillShow(_:)), name: .UIKeyboardWillShow, object: nil) 
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyBoardWillHide(_:)), name: .UIKeyboardWillHide, object: nil) 
} 

をしてから:

私は、次のコードを使用してい

@objc func keyBoardWillShow(_ notification: NSNotification) { 
    let userInfo:NSDictionary = notification.userInfo! as NSDictionary 
    let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue 
    let keyboardRectangle = keyboardFrame.cgRectValue 
    let keyboardHeight = keyboardRectangle.height 

    UIView.animate(withDuration: 0.4) { 
     self.commentViewBottomConstraint.constant = keyboardHeight 
     self.view.layoutIfNeeded() 
    } 
} 
@objc func keyBoardWillHide(_ notification: NSNotification) { 
    UIView.animate(withDuration: 0.4) { 
     self.commentViewBottomConstraint.constant = 0 
     self.view.layoutIfNeeded() 
    } 
} 

問題は、キーボードの高さが正しくないようだということです。実際、ビューの下部はキーボードと揃っていません。ビューとキーボードの間にはスペースがあります。

enter image description here

正直なところ、私は私が間違っているのかを理解していない...

は助けてくれてありがとう!

答えて

0

問題は、下部の制約が安全領域に関連しているということでした。 だから私はこれを追加することによって、それを固定している:

@objc func keyBoardWillShow(_ notification: NSNotification) { 
    let userInfo:NSDictionary = notification.userInfo! as NSDictionary 
    let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue 
    let keyboardRectangle = keyboardFrame.cgRectValue 
    let keyboardHeight = keyboardRectangle.height 
    let safeAreaHeight = self.view.safeAreaInsets.bottom 

    UIView.animate(withDuration: 0.4) { 
     self.commentViewBottomConstraint.constant = keyboardHeight - safeAreaHeight 
     self.view.layoutIfNeeded() 
    } 
} 

let safeAreaHeight = self.view.safeAreaInsets.bottom 
self.commentViewBottomConstraint.constant = keyboardHeight - safeAreaHeight 

ここでは、完全なコードです

関連する問題