2016-05-31 95 views
1

我已創建的UIScrollView的延伸,其中當用戶選擇一個文本字段和出現的鍵盤,文本字段會向上滾動,如果它是在鍵盤的方式。我有工作了UITextField,但它似乎並沒有與UITextView工作。我已經搜索了很多帖子在stackoverflow,但似乎無法找到任何幫助。下面是該擴展的代碼:的UITextView避免鍵盤滾動

extension UIScrollView { 

func respondToKeyboard() { 
    self.registerForKeyboardNotifications() 
} 


func registerForKeyboardNotifications() { 
    // Register to be notified if the keyboard is changing size i.e. shown or hidden 
    NSNotificationCenter.defaultCenter().addObserver(
     self, 
     selector: #selector(keyboardWasShown(_:)), 
     name: UIKeyboardWillShowNotification, 
     object: nil 
    ) 
    NSNotificationCenter.defaultCenter().addObserver(
     self, 
     selector: #selector(keyboardWillBeHidden(_:)), 
     name: UIKeyboardWillHideNotification, 
     object: nil 
    ) 
} 

func keyboardWasShown(notification: NSNotification) { 
    if let info = notification.userInfo, 
     keyboardSize = info[UIKeyboardFrameBeginUserInfoKey]?.CGRectValue.size { 

     self.contentInset.bottom = keyboardSize.height + 15 
     self.scrollIndicatorInsets.bottom = keyboardSize.height 

     var frame = self.frame 
     frame.size.height -= keyboardSize.height 
    } 
} 

func keyboardWillBeHidden(notification: NSNotification) { 
    self.contentInset.bottom = 0 
    self.scrollIndicatorInsets.bottom = 0 
} 

在我的視圖控制器我只想把它想:

scrollView.respondToKeyboard() 

有人能指出我的我怎麼能實現UITextView作爲一個正確的方向如果鍵盤擋道,擴展可以向上移動?

回答

0

您可以嘗試使用UITextView的委託方法。看看這個link瞭解更多詳情。如需快速查看教程here

+0

感謝您的鏈接。所以,現在我有** UIScrollView **的擴展,我應該更改擴展名,以便它是** UITextView **和** UITextField **的擴展? @iOS Geek – coderdojo

+0

只是認爲它可能是一種更好的方式,而不是 – coderdojo

+0

@coderdojo - 如果您在視圖控制器中使用委託處理鍵盤,則不需要擴展。 –

0

對於我這種解決方案的UITextView工作正常。也許你可以更新此滾動視圖

// keyboard visible?? 
lazy var keyboardVisible = false 
// Keyboard-Height 
lazy var keyboardHeight: CGFloat = 0 

func updateTextViewSizeForKeyboardHeight(keyboardHeight: CGFloat) { 
    textView.contentInset.bottom = keyboardHeight 
    self.keyboardHeight = keyboardHeight 
} 

func keyboardDidShow(notification: NSNotification) { 
    if let rectValue = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue { 
     if keyboardVisible == false { 
      let keyboardSize = rectValue.CGRectValue().size 
      keyboardVisible = true 
      updateTextViewSizeForKeyboardHeight(keyboardSize.height)     
     } 
    } 
} 

func keyboardDidHide(notification: NSNotification) { 
    if keyboardVisible { 
     keyboardVisible = false 
     updateTextViewSizeForKeyboardHeight(0) 
    } 
}