切换UITextField(Swift)时出现键盘调整视图 [英] Adjust View for keyboard appears when switching UITextField (Swift)

查看:278
本文介绍了切换UITextField(Swift)时出现键盘调整视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个UIView,一个是Main,另一个是在出现键盘时向上移动(第二个UIView有两个文本字段).我已经用以下代码做到了这一点:

I have two UIView's , the Main one and one which will move up when the keyboard appears (Second UIView has two textfields). I've managed to do this with the following code:

LoginViewController.swift:

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时,视图会自动向下移动.我在做什么错了?

My big problems is that because the movement of the UIView depends on the keyboard notification, when the user taps one TextField it moves up as it should, but when he taps the second one the view moves down automatically. What Im I doing wrong?

正在发生的事情:键盘错误Gif

在这里回答了这个问题,但是我需要Swift语言的解决方案.

This question was answered over here , but I need the solution for Swift language.

推荐答案

设置文本字段的委托并实现以下方法

Set delegate of your textfield and implement the below methods

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

这篇关于切换UITextField(Swift)时出现键盘调整视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆