Swift 5鍵盤擋住輸入框的問題
2 min readJan 29, 2018
還有另一種方式也可參考我這篇動態獲取鍵盤高度
是用改變輸入框的layout的方式,還會有動畫的效果
先將要改變的layout約束outlet:
@IBOutlet weak var myConstraintY: NSLayoutConstraint!
再創一個方法:
@objc func keyboardWillChange(_ notification: Notification) { if let userInfo = notification.userInfo{ let value = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! Double let curve = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as! UInt let frame = value?.cgRectValue
//let intersection = frame?.intersection(self.view.frame)因為範例是將textField放在最下面才需要這個 self.myConstraintY.constant = -50//-(intersection?.height)!因為我是將textField置中所以改以移動50就可以 UIView.animate(withDuration: duration, delay: 0.0, options: UIView.AnimationOptions(rawValue: curve), animations: self.view.layoutIfNeeded, completion: nil) }}
當然鍵盤隱藏時要移回來的方法也要寫,因為幾乎一樣,所以就不貼上了,以下為效果圖。