簡體   English   中英

當鍵盤顯示UITextView而不是同一視圖上的UITextField時,滾動視圖

[英]Scroll view when keyboard appears for UITextView, but not for the UITextField that's on the same view

當我開始編輯UITextView時,我正在使用此代碼向上滾動視圖。

override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(Login.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(Login.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

}

func keyboardWillShow(notification: NSNotification) {

    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height
        }
    }

}

func keyboardWillHide(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y != 0{
            self.view.frame.origin.y += keyboardSize.height
        }
    }
}

但是,我在該視圖的頂部也有一個UITextField ,當我開始對其進行編輯時,該視圖也會滾動。 我不希望這種情況發生。 如何將我的代碼更改為僅在激活UITextView鍵盤時滾動而不在激活UITextField鍵盤時滾動?

嘗試這段代碼,用戶使用textview delgate

// scrollBy-傳遞您希望在鍵盤出現時滾動滾動視圖的高度

 func textViewDidBeginEditing(_ textView: UITextView)
    {
         scrView.setContentOffset(CGPoint.init(x: 0, y: scrollBy), animated: true)

     }

    func textViewDidEndEditing(_ textView: UITextView)
    {
        scrView.setContentOffset(CGPoint.init(x: 0, y: 0), animated: true)

        self.view.endEditing(true);
    }

我建議您應該在項目中添加TPkeyboard File而不是編碼,這會在需要時切換鍵盤

暫無
暫無

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

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