標籤:
看這篇文章之前,建議讀者先瞭解一下通知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 = true10 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.height10 self.keyboardHeaderView.frame = CGRect(x: 0,y: y,width: DeviceFrame.width,height: 30)11 })12 }13 14 //keyboard will hide15 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 }
實現這個功能之後,我們一般都是在上面現實一個鍵盤的工具條用於實現表情鍵盤。
iOS開發——Swift實戰篇&通知之鍵盤的現實與隱藏(加鍵盤工具條)