swift之textView和textField输入时键盘隐藏

1 首先添加协议

在需要的文件中添加俩个协议为:UITextFieldDelegateUITextViewDelegate俩个协议

2 解决textview遮挡键盘代码

/**
解决textview遮挡键盘代码

:param: textView textView description
*/
func textViewDidBeginEditing(textView: UITextView) {
    var frame:CGRect = textView.frame
    var offset:CGFloat = frame.origin.y + 100 - (self.view.frame.size.height-330)
    
    if offset > 0  {
        
        self.view.frame = CGRectMake(0.0, -offset, self.view.frame.size.width, self.view.frame.size.height)
    }
    
    println("移动键盘")
}

3 恢复屏幕

/**
恢复视图

:param: textView textView description
*/
func textViewDidEndEditing(textView: UITextView) {
    self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
    println("恢复视图")
}

4 解决textfield遮挡键盘代码

/**

 解决textField遮挡键盘代码
:param: textField textField description
*/
func textFieldDidBeginEditing(textField: UITextField) {
    //
    var frame:CGRect = textField.frame
    var offset:CGFloat = frame.origin.y + 100 - (self.view.frame.size.height-216)
    
    if offset > 0  {
        
        self.view.frame = CGRectMake(0.0, -offset, self.view.frame.size.width, self.view.frame.size.height)
    }
}

5 恢复屏幕

/**
恢复视图

:param: textField textField description
*/
func textFieldDidEndEditing(textField: UITextField) {
    //
    self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
    
}

6 隐藏键盘

override func touchesBegan(touches: Set, withEvent event: UIEvent) {
    releaseActivityName.resignFirstResponder()
    releaseActivityStartTime.resignFirstResponder()
    releaseActivityEndTime.resignFirstResponder()
    releaseActivityLocation.resignFirstResponder()
    releaseActivityNumber.resignFirstResponder()
    releaseActivityPhone.resignFirstResponder()
    releaseActivityNote.resignFirstResponder()
}

7 开始使用

只需要在使用的控件时,使其该控件的协议指向view

    self.releaseActivityNote.delegate = self
    self.releaseActivityName.delegate = self
    self.releaseActivityNumber.delegate = self
    self.releaseActivityPhone.delegate = self

你可能感兴趣的:(swift之textView和textField输入时键盘隐藏)