切换UITextField(Swift)时出现键盘调整视图
我有两个UIView的,主要的一个,当键盘出现时会向上移动(第二个UIView有两个文本框)。 我设法用下面的代码做到这一点:
LoginViewController.swift:
override func viewDidLoad() { super.viewDidLoad() self.originalCenter = self.contentView.center; NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidShow:", name: UIKeyboardDidShowNotification, object: nil) } func keyboardDidShow(notification: NSNotification) { UIView.animateWithDuration(1.0, animations: { self.contentView.center = CGPointMake(self.originalCenter.x, self.originalCenter.y - 40); }) }
我最大的问题在于,因为UIView的移动取决于键盘通知,所以当用户点击一个TextField时,它会上移,但是当他点击第二个TextField时,视图会自动下移。 我在做什么错了?
这是发生了什么事: 键盘错误Gif
这个问题在这里得到了回答,但是我需要Swift语言的解决scheme。
创build一个实例variables,并检查键盘是否被激活:class ViewController:UIViewController,UITextFieldDelegate {
var _keyboardActivated: Bool = false override func viewDidLoad() { super.viewDidLoad() registerForKeyboardNotifications() } override func viewWillDisappear(animated: Bool) { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } func registerForKeyboardNotifications() { NSNotificationCenter.defaultCenter().addObserver( self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver( self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil) } func keyboardWillShow(notification: NSNotification) { if (!_keyboardActivated) { // do stuff } _keyboardActivated = true } func keyboardWillBeHidden(notification: NSNotification) { _keyboardActivated = false } }
设置你的文本字段的代表并实现下面的方法
func textFieldDidBeginEditing(textField: UITextField) { animateViewMoving(true, moveValue: 100) } func textFieldDidEndEditing(textField: UITextField) { animateViewMoving(false, moveValue: 100) } func animateViewMoving (up:Bool, moveValue :CGFloat){ var movementDuration:NSTimeInterval = 0.3 var movement:CGFloat = ( up ? -moveValue : moveValue) UIView.beginAnimations( "animateView", context: nil) UIView.setAnimationBeginsFromCurrentState(true) UIView.setAnimationDuration(movementDuration ) self.view.frame = CGRectOffset(self.view.frame, 0, movement) UIView.commitAnimations() }
参考: http : //www.jogendra.com/2015/01/uitextfield-move-up-when-keyboard.html