![](/img/trans.png)
[英]Move UITextField/View up when keyboard appears, but only if TextFiel is hidden
[英]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.