看这篇文章之前,建议读者先了解一下通知NSNotifation的通信原理
不好描述,我先上图:
就是点击“完成”可以隐藏键盘和自己,键盘出来时他们也跟着出来,对,就是这种效果,非常常用
1,设置keyboardHeaderview和“完成”(这里的self.keyboardHeaderView设置成了self对象)
1 self.keyboardHeaderView.frame = CGRect(x: 0,y: DeviceFrame.height+StatusBarFrame.height,width: DeviceFrame.width,height: 30)
2 self.keyboardHeaderView.backgroundColor = UIColor(white:0, alpha: 0.6)
3 var hiddenKeyBoardLabel:UILabel = UILabel(frame:CGRect(x:0,y:0,width:DeviceFrame.width-10,height:30))
4 hiddenKeyBoardLabel.text = "完成"
5 hiddenKeyBoardLabel.textColor = UIColor.blueColor()
6 hiddenKeyBoardLabel.textAlignment = .Right
7
8 var tap:UITapGestureRecognizer = UITapGestureRecognizer(target:self,action:Selector("hideKeyboard:"))
9 self.keyboardHeaderView.userInteractionEnabled = true
10 self.keyboardHeaderView.addGestureRecognizer(tap)
11
12 self.keyboardHeaderView.addSubview(hiddenKeyBoardLabel)
13 self.view.addSubview(self.keyboardHeaderView)
点击“完成”,调用方法(这里的self.content是一个UITextField或者UITextView对象)
1 //hide keyboard 2 func hideKeyboard(sender:AnyObject){ 3 self.content.resignFirstResponder() 4 }
2,设置keyboard监听事件:
1 NSNotificationCenter.defaultCenter().addObserver(self,selector:Selector("keyboardWillShow:"),name:UIKeyboardWillShowNotification,object:nil)
2 NSNotificationCenter.defaultCenter().addObserver(self,selector:Selector("keyboardWillHide:"),name:UIKeyboardWillHideNotification,object:nil)
//下面就是键盘隐藏时触发的事件,我在这个事件里面完成我们想要的功能(就是设置keyboardHeaderview跟着键盘隐藏和出现)
1 //Keyboard will show
2 func keyboardWillShow(sender:NSNotification){
3 let userInfo = sender.userInfo
4 let keyboardInfo : (AnyObject!) = userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey)
5 let keyboardRect:CGRect = keyboardInfo.CGRectValue() as CGRect
6 let height = keyboardRect.size.height as Float
7
8 UIView.animateWithDuration(0.3, animations: {
9 var y:Float = DeviceFrame.height+StatusBarFrame.height - height-self.keyboardHeaderView.frame.height
10 self.keyboardHeaderView.frame = CGRect(x: 0,y: y,width: DeviceFrame.width,height: 30)
11 })
12 }
13
14 //keyboard will hide
15 func keyboardWillHide(sender:NSNotification){
16 UIView.animateWithDuration(0.3, animations: {
17 self.keyboardHeaderView.frame = CGRect(x: 0,y: DeviceFrame.height+StatusBarFrame.height,width: DeviceFrame.width,height: 30)
18 })
19 }
实现这个功能之后,我们一般都是在上面现实一个键盘的工具条用于实现表情键盘。