显示键盘时移动UITextField

时间:2018-07-19 04:17:45

标签: ios swift scrollview nsnotificationcenter

当键盘显示时,我正在尝试移动UITextFields。现在,我看了视频并阅读了有关如何做的文章。我还没有看到使用文本字段本身的代码,而是使用了文本字段的底部约束。这是我的代码的video,下面是我的代码。

class ViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var nameTF: UITextField!
@IBOutlet weak var emailTF: UITextField!

var selectedTextField: UITextField?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    createKeyboardNotification()
}

func createKeyboardNotification() {
    NotificationCenter.default.addObserver(self, selector: #selector(respondToKeyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(respondToKeyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

@objc func respondToKeyboardWillShow(notification: Notification) {
    adjustHeightForTextFields(isKeyboardHidden: false, notification: notification, textField: selectedTextField)
}

@objc func respondToKeyboardWillHide(notification: Notification) {
   adjustHeightForTextFields(isKeyboardHidden: true, notification: notification, textField: selectedTextField)
}


func adjustHeightForTextFields(isKeyboardHidden: Bool, notification: Notification, textField: UITextField?) {

    guard let userInfo = notification.userInfo else { return }
    let keyboardFrameRect = userInfo[UIKeyboardFrameEndUserInfoKey] as! CGRect

    if let textField = textField {
        let textFieldYPosition = textField.frame.origin.y

        if view.frame.maxY - textFieldYPosition > keyboardFrameRect.height {
            UIView.animate(withDuration: 0.25) {
                textField.frame.origin.y = (self.view.frame.maxY - textField.frame.size.height - keyboardFrameRect.height - 8)
            }
        }
        else {
            UIView.animate(withDuration: 0.25) {
                let difference = textFieldYPosition - keyboardFrameRect.height
                textField.frame.origin.y = difference + 16 + self.view.safeAreaInsets.bottom - 8
            }
        }
    }
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

func textFieldDidBeginEditing(_ textField: UITextField) {
    switch textField {
    case nameTF:
        print("NAME")
        selectedTextField = nameTF
        break
    case emailTF:
        print("EMAIL")
        selectedTextField = emailTF
        break
    default:
        break
    }
}
}

如果您看过视频,我会遇到一些奇怪的事情。首先,当您点击文本字段时,它的工作原理与假定的相同,但是当您开始键入文本字段时,它就会消失。当我使用文本字段底部约束时,我没有遇到过。现在第二部分是当已经显示键盘时,文本字段无法正确设置动画,直到您单击两次。

现在我不使用滚动视图,但是想推送全部内容,或者我需要使用滚动视图。如果您看一下此video,则可以通过推送内容来更好地理解我的意思。

非常感谢您提供的任何帮助,谢谢。 :)

2 个答案:

答案 0 :(得分:0)

仅当底部的textField处于活动状态时,才需要向上移动视图。

//Create a global variable to use as our keyboardHeight
var keyboardHeight: CGFloat = 0.0

override func viewDidLoad() {
        super.viewDidLoad()

    //Set the delegate only for the emailTF
    emailTF.delegate = self

    //Set up an observer. This will help us calculate keyboard height dynamically, depending on the iPhone the app runs on.
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}

@objc private func keyboardWillShow(notification: NSNotification) {
    if let keyboardRectValue = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        keyboardHeight = keyboardRectValue.height
    }
}
  

然后在textField处于活动/非活动状态时上下移动视图。

func textFieldDidBeginEditing(_ textField: UITextField) {
        print("MOVE VIEW UP")
        if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardHeight
        }
}

func textFieldDidEndEditing(_ textField: UITextField) {
        print("MOVE VIEW DOWN")
        if self.view.frame.origin.y != 0{
            self.view.frame.origin.y += keyboardHeight
        }
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        print("MOVE VIEW DOWN")
        if self.view.frame.origin.y != 0{
            self.view.frame.origin.y += keyboardHeight
        }
    return true
}

这绝对可以工作。祝你好运!

答案 1 :(得分:0)

我同意并不总是很清楚。我们在应用程序中执行此操作,并使用了滚动视图。我们将整个页面嵌入到滚动视图中。然后,我们将滚动视图的底部向上移动。滚动视图易于实现。

@objc func keyboardWillShow(notification: NSNotification) {
    // Only deal with this if the window is active and visible.
    if !self.isViewLoaded || self.view.window == nil {
        return
    }
    if let userInfo = notification.userInfo {
        let keyboardFrame = userInfo[UIKeyboardFrameEndUserInfoKey] as! CGRect
        scrollView.frame = CGRect(x: view.frame.origin.x,y: view.frame.origin.y,width: view.frame.width, height: view.frame.height - keyboardFrame.height - 64)

     }
    self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)))
}

当键盘消失时:

@objc func keyboardWillHide(notification: NSNotification) {
    scrollView.frame = scrollViewOriginalFrame
}