Swift - 键盘弹起,遮挡输入框
方式一:
extension LoginViewController:UITextFieldDelegate {
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
//键盘收回,view放下
UIView.animateWithDuration(0.4, animations: {
self.view.frame.origin.y = 0
})
return true
}
func textFieldDidBeginEditing(textView:UITextField) {
//view弹起跟随键盘,高可根据自己定义
UIView.animateWithDuration(0.4, animations: {
self.view.frame.origin.y = -150
})
}
}
方式二:
// 键盘改变
func textFieldDidBeginEditing(textField: UITextField) {
animateViewMoving(true, moveValue: 300)
}
func textFieldDidEndEditing(textField: UITextField) {
animateViewMoving(false, moveValue: 300)
}
func animateViewMoving (up:Bool, moveValue :CGFloat){
dispatch_after(UInt64(0.3), dispatch_get_main_queue()) {
let movement:CGFloat = ( up ? -moveValue : moveValue)
UIView.beginAnimations( "animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
self.view.frame = CGRectOffset(self.view.frame, 0, movement)
UIView.commitAnimations()
}
}
// 点击输入框收起键盘
func textFieldShouldReturn(textField: UITextField) -> Bool {
//收起键盘
textField3.resignFirstResponder()
//打印出文本框中的值
print(textField3.text)
return true
}
// 点击屏幕收起键盘
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
view.endEditing(true)
}