本文示例在一个父页面点击某个按钮时增加一个子视图,子视图内有个文本编辑框,当文本视图为第一响应者时,键盘从下而上推动视图上移,同时子视图也随之上移,背景此时变为半透明。输入完成确定或者点击背景放弃输入时,子视图随键盘下移最后消失。
首先注册键盘消息
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardFrameWillShowNotification:"), name:UIKeyboardWillShowNotification, object: nil)
当 self.inputTextFiled.becomeFirstResponder() 被调用而成为第一响应者时,会发消息 UIKeyboardWillShowNotification,这里增加背景视图,使点击之前父页面不会响应,同时为背景增加响应,点击时键盘下移。
func keyboardFrameWillShowNotification(notification:NSNotification) {
let kbRect:CGRect =(notification.userInfo!)[UIKeyboardFrameEndUserInfoKey]!.CGRectValue()
let duration =(notification.userInfo!)[UIKeyboardAnimationDurationUserInfoKey]as! Double
let y = self.superview!.convertRect(kbRect, fromView:nil).origin.y //转换为相对应父视图的坐标
var frame = self.frame
frame.origin.y = y - frame.size.height
if(self.maskBackgroundView ==nil)
{
self.maskBackgroundView =UIView(frame: CGRectMake(0,0, frame.width,self.superview!.frame.height)) //在父视图上增加背景视图
self.maskBackgroundView!.backgroundColor =UIColor.blackColor()
self.maskBackgroundView!.alpha =0.0
let tapMaskView = UITapGestureRecognizer(target: self, action:Selector("tapMaskView:"))
self.maskBackgroundView!.addGestureRecognizer(tapMaskView)
}
UIView.animateWithDuration(duration, animations:{ //视图边框修改,背景半透明
self.frame = frame
self.maskBackgroundView?.alpha =0.5
self.superview!.insertSubview(self.maskBackgroundView!, belowSubview:self)
})
}
func tapMaskView(gesture: UIGestureRecognizer) {
self.hideInputView()
}
private func hideInputView() {
self.maskBackgroundView?.alpha=0
var frame = self.frame
UIView.animateWithDuration(0.3, animations: {
self.inputTextFiled.resignFirstResponder()
self.frame =CGRectMake(0,self.superview!.frame.height, frame.width, frame.size.height)
}){[unowned self] (completion) -> Void in
self.inputTextFiled.text =nil
self.hidden =true
self.maskBackgroundView?.removeFromSuperview()
self.removeFromSuperview()
}
}
PS : 对于使用 presentViewController 显示视图时,iPad 模式视图下,视图本事会在键盘弹出后调整边框位置,导致在UIKeyboardDidShowNotification 和 UIKeyboardWillShowNotification 时转化为模式视图的边框位置不同。在使用时注意。如有必要,应选择 UIKeyboardDidShowNotification,不过这样没有动态移动的效果,暂时没有解决方法。