iOS开发——Swift实战篇&通知之键盘的现实与隐藏(加键盘工具条)

看这篇文章之前,建议读者先了解一下通知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     }

实现这个功能之后,我们一般都是在上面现实一个键盘的工具条用于实现表情键盘。

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。