当键盘出现在ios9

时间:2016-02-17 17:00:52

标签: swift uiscrollview uitextview ios9

我正在尝试在键盘出现时向上滚动嵌入在UIScrollView中的元素(UIImage和UITextView)。

我的观点包含以下内容:

class EditProfileViewController: UIViewController, UITextViewDelegate {
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var activeTextView: UIView!
    @IBOutlet weak var scrollView: UIScrollView!

当视图加载时,我注册了委托并设置了键盘观察者:

self.textView.delegate = self

NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardDidHideNotification, object: nil)

方法如下(感谢Apple doc):

func  textViewDidBeginEditing(textView: UITextView) {
    self.activeTextView = textView
}

func textViewDidEndEditing(textView: UITextView) {
    self.activeTextView = nil
}

func keyboardWasShown(notification: NSNotification){
    var userInfo = notification.userInfo!
    let keyboardSize = userInfo[UIKeyboardFrameBeginUserInfoKey]!.CGRectValue.size
    let contentInsets = UIEdgeInsetsMake(0.0, 0.0, (keyboardSize.height), 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect = self.view.frame
    aRect.size.height -= (keyboardSize.height)
    //if ( !CGRectContainsPoint(aRect, self.activeTextView.frame.origin)) {
        self.scrollView.scrollRectToVisible(self.activeTextView.frame, animated: true)
    //}
}

func keyboardWillBeHidden(notification: NSNotification) {
    let contentInsets = UIEdgeInsetsZero
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
}

但是当我点击我的UITextView以显示键盘时,会发生没有。什么都没有滚动,所以键盘屏蔽我的UITextView。

我的代码有什么问题?

感谢您的反馈。

托马斯

0 个答案:

没有答案