切换UITextField(Swift)时出现调整键盘视图

时间:2015-01-02 06:18:10

标签: ios swift uiview keyboard uitextfield

我有两个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时它会向上移动,但是当他点击第二个时,视图会自动向下移动。我做错了什么?

这就是发生的事情:Keyboard Error Gif

这个问题已经回答over here,但我需要Swift语言的解决方案。

2 个答案:

答案 0 :(得分:0)

创建实例变量并检查键盘是否已激活:     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
}
}

答案 1 :(得分:0)

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

#app/models/message.rb
class Message < ActiveRecord::Base
   #columns id | student_id | coach_id | message | read | created_at | updated_at
   belongs_to :student
   belongs_to :coach
end

#app/models/coach.rb
class Coach < ActiveRecord::Base
   has_many :messages
end

#app/models/student.rb
class Student < ActiveRecord::Base
   has_many :messages
end

参考:http://www.jogendra.com/2015/01/uitextfield-move-up-when-keyboard.html