技术文章分类(180)

技术随笔(11)

swift UIKeyboard监听,隐藏

看这篇文章之前,建议读者先了解一下通知NSNotifation的通信原理

不好描述,我先上图:

就是点击“完成”可以隐藏键盘和自己,键盘出来时他们也跟着出来,对,就是这种效果,非常常用

1,设置keyboardHeaderview和“完成”(这里的self.keyboardHeaderView设置成了self对象)

        self.keyboardHeaderView.frame = CGRect(x: 0,y: DeviceFrame.height+StatusBarFrame.height,width: DeviceFrame.width,height: 30)
            self.keyboardHeaderView.backgroundColor = UIColor(white:0, alpha: 0.6)
            var hiddenKeyBoardLabel:UILabel = UILabel(frame:CGRect(x:0,y:0,width:DeviceFrame.width-10,height:30))
            hiddenKeyBoardLabel.text = "完成"
            hiddenKeyBoardLabel.textColor = UIColor.blueColor()
            hiddenKeyBoardLabel.textAlignment = .Right
            
            var tap:UITapGestureRecognizer = UITapGestureRecognizer(target:self,action:Selector("hideKeyboard:"))
            self.keyboardHeaderView.userInteractionEnabled = true
            self.keyboardHeaderView.addGestureRecognizer(tap)
            
            self.keyboardHeaderView.addSubview(hiddenKeyBoardLabel)
            self.view.addSubview(self.keyboardHeaderView)

点击“完成”,调用方法(这里的self.content是一个UITextField或者UITextView对象)

    //hide keyboard
    func hideKeyboard(sender:AnyObject){
        self.content.resignFirstResponder()
    }

 

2,设置keyboard监听事件:

            NSNotificationCenter.defaultCenter().addObserver(self,selector:Selector("keyboardWillShow:"),name:UIKeyboardWillShowNotification,object:nil)
            NSNotificationCenter.defaultCenter().addObserver(self,selector:Selector("keyboardWillHide:"),name:UIKeyboardWillHideNotification,object:nil)

//下面就是键盘隐藏时触发的事件,我在这个事件里面完成我们想要的功能(就是设置keyboardHeaderview跟着键盘隐藏和出现)

    //Keyboard will show
    func keyboardWillShow(sender:NSNotification){
        let userInfo = sender.userInfo
        let keyboardInfo : (AnyObject!) = userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey)
        let keyboardRect:CGRect = keyboardInfo.CGRectValue() as CGRect
        let height = keyboardRect.size.height as Float
        
        UIView.animateWithDuration(0.3, animations: {
            var y:Float = DeviceFrame.height+StatusBarFrame.height - height-self.keyboardHeaderView.frame.height
            self.keyboardHeaderView.frame = CGRect(x: 0,y: y,width: DeviceFrame.width,height: 30)
        })
    }
    
    //keyboard will hide
    func keyboardWillHide(sender:NSNotification){
        UIView.animateWithDuration(0.3, animations: {
            self.keyboardHeaderView.frame = CGRect(x: 0,y: DeviceFrame.height+StatusBarFrame.height,width: DeviceFrame.width,height: 30)
        })
    }
posted @ 2014-07-17 15:20  坤哥MartinLi  阅读(1478)  评论(0编辑  收藏  举报