2016-05-31 48 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) 
    } 
}