UITextView避免键盘滚动

时间:2016-05-31 12:07:02

标签: ios swift uiscrollview uitextview

我创建了UIScrollView的扩展名,当用户选择文本字段并出现键盘时,如果文本字段位于键盘中,则文本字段将向上滚动。我让它适用于UITextField,但它似乎不适用于UITextView。我在stackoverflow上搜索过很多帖子,但似乎无法找到任何帮助。以下是扩展程序的代码:

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作为一个扩展,以便在键盘挡住的情况下向上移动,这是正确的方向吗?

2 个答案:

答案 0 :(得分:0)

您可以尝试使用UITextView委托方法。有关详细信息,请查看此link。对于swift,请查看教程here

答案 1 :(得分:0)

对我来说这个解决方案适用于UITextView。也许你可以为Scrollview更新这个

// 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)
    }
}
相关问题