简体   繁体   English

显示键盘时移动UITextField

[英]Moving UITextFields when keyboard shows

I am trying to move UITextFields when the Keyboard shows. 我试图在显示键盘时移动UITextFields。 Now I've seen videos and read articles on how to do it. 现在,我看了视频并阅读了有关如何做的文章。 I haven't seen one that uses the textfield itself, rather they use the bottom constraint of the textfield. 我还没有看到使用文本字段本身的代码,而是使用了文本字段的底部约束。 Here is a video of what my code does, below is my code. 这是我的代码的视频 ,下面是我的代码。

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
    }
}
}

If you have seen the video, I've come across some strange things. 如果您看过视频,我遇到了一些奇怪的事情。 First when you tap on the textfield it works like its suppose to, but when you start typing the textfield just disappears. 首先,当您点击文本字段时,它的工作原理与假定的相同,但是当您开始键入文本字段时,它就会消失。 I didn't come across this when I was using the textfield bottom constraint. 当我使用文本字段底部约束时,我没有遇到过。 Now the second part is when the keyboard is already shown the textfield doesn't animate correctly, until you click it twice. 现在第二部分是当已经显示键盘时,文本字段无法正确设置动画,直到您单击两次。

Now I am not using a scrollview, but would like to push the whole content or would I need to use a scrollview. 现在我不使用滚动视图,但想推送全部内容,或者我需要使用滚动视图。 If you take a look at this video , you can better understand what I mean by wanting to push the content. 如果您观看此视频 ,则可以通过推送内容更好地理解我的意思。

Would really appreciate any help provided, Thanks. 非常感谢提供的任何帮助,谢谢。 :) :)

You need to move the view up only when the textField on the bottom becomes active. 仅当底部的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
    }
}

Then move the view up and down when the textField becomes active/inactive. 然后在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
}

This should definitely work. 这绝对应该工作。 Good luck! 祝好运!

I agree that it's not clear always. 我同意并不总是很清楚。 We do this in our app and we used a scroll view. 我们在应用程序中执行此操作,并使用了滚动视图。 We embed the entire page in the scroll view. 我们将整个页面嵌入到滚动视图中。 Then we move the bottom of the scroll view up. 然后,我们将滚动视图的底部向上移动。 Scrollviews are easy to implement. 滚动视图易于实现。

@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)))
}

And when the keyboard disappears: 当键盘消失时:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM