//键盘将要展示时触发的方法 func keyboardWillShow(noti:NSNotification){ //获取通知信息 let info:Dictionary = noti.userInfo! //获取信息中的键盘尺寸和位置信息 let value:NSValue = info[UIKeyboardFrameBeginUserInfoKey] as! NSValue //获取键盘动画的时间信息 let value2:NSValue = info[UIKeyboardAnimationDurationUserInfoKey] as! NSValue let keyboardSize = value.CGRectValue() let height = keyboardSize.height var time:NSTimeInterval=0 value2.getValue(&time) //重设约束 textViewBottom.constant = height //动画展示 UIView.animateWithDuration(time) { () -> Void in self.view.layoutIfNeeded() } } //键盘将要隐藏时触发的方法 func keyboardWillHidden(noti:NSNotification){ let info:Dictionary = noti.userInfo! let value2:NSValue = info[UIKeyboardAnimationDurationUserInfoKey] as! NSValue var time:NSTimeInterval=0 value2.getValue(&time) textViewBottom.constant = 0 UIView.animateWithDuration(time) { () -> Void in self.view.layoutIfNeeded() } }
监听的键盘状态发送的通知中,会传递进来许多键盘信息,可取的键值如下:
1 2 3 4 5 6 7 8 9 10
@available(iOS 3.2, *) public let UIKeyboardFrameBeginUserInfoKey: String //键盘的初始位置尺寸 为CGRect类型的NSValue值 @available(iOS 3.2, *) public let UIKeyboardFrameEndUserInfoKey: String // 键盘的末位位置尺寸 为CGRect类型的NSValue值 @available(iOS 3.0, *) public let UIKeyboardAnimationDurationUserInfoKey: String // 键盘动画时间 double类型的NSValue @available(iOS 3.0, *) public let UIKeyboardAnimationCurveUserInfoKey: String // 键盘动画效果 (UIViewAnimationCurve)枚举类型的NSNumber值 @available(iOS 9.0, *) public let UIKeyboardIsLocalUserInfoKey: String //与多任务相关 判断键盘是否属于当前应用 iOS9后可用
可以监听的与键盘相关信息的通知有如下几种:
1 2 3 4 5 6 7 8
public let UIKeyboardWillShowNotification: String//键盘将要出现 public let UIKeyboardDidShowNotification: String//键盘已经出现 public let UIKeyboardWillHideNotification: String//键盘将要隐藏 public let UIKeyboardDidHideNotification: String//键盘已经隐藏 @available(iOS 5.0, *) public let UIKeyboardWillChangeFrameNotification: String//键盘frame将要改变 @available(iOS 5.0, *) public let UIKeyboardDidChangeFrameNotification: String//键盘frame已经改变