簡體   English   中英

顯示鍵盤時移動UITextField

[英]Moving UITextFields when keyboard shows

我試圖在顯示鍵盤時移動UITextFields。 現在,我看了視頻並閱讀了有關如何做的文章。 我還沒有看到使用文本字段本身的代碼,而是使用了文本字段的底部約束。 這是我的代碼的視頻 ,下面是我的代碼。

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

如果您看過視頻,我遇到了一些奇怪的事情。 首先,當您點擊文本字段時,它的工作原理與假定的相同,但是當您開始鍵入文本字段時,它就會消失。 當我使用文本字段底部約束時,我沒有遇到過。 現在第二部分是當已經顯示鍵盤時,文本字段無法正確設置動畫,直到您單擊兩次。

現在我不使用滾動視圖,但想推送全部內容,或者我需要使用滾動視圖。 如果您觀看此視頻 ,則可以通過推送內容更好地理解我的意思。

非常感謝提供的任何幫助,謝謝。 :)

僅當底部的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
}

這絕對應該工作。 祝好運!

我同意並不總是很清楚。 我們在應用程序中執行此操作,並使用了滾動視圖。 我們將整個頁面嵌入到滾動視圖中。 然后,我們將滾動視圖的底部向上移動。 滾動視圖易於實現。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM