键盘在屏幕上时滚动文本视图

时间:2015-11-27 11:37:29

标签: ios swift uiscrollview uitextview uitextviewdelegate

我在视图控制器上有一个方法,如果键盘在屏幕上,则在聚焦时向上滚动文本字段。

我试图在不同的控制器上做同样的事情,但是使用textview但它不起作用。

尝试:

func keyboardOnScreen(notification: NSNotification){
        // Retrieve the size and top margin (inset is the fancy word used by Apple)
        // of the keyboard displayed.
        let info: NSDictionary  = notification.userInfo!
        let kbSize = info.valueForKey(UIKeyboardFrameEndUserInfoKey)?.CGRectValue.size
        let contentInsets: UIEdgeInsets  = UIEdgeInsetsMake(0.0, 0.0, kbSize!.height, 0.0)

        scrollView.contentInset = contentInsets
        scrollView.scrollIndicatorInsets = contentInsets

        var aRect: CGRect = self.view.frame
        aRect.size.height -= kbSize!.height

        //you may not need to scroll, see if the active field is already visible
        print("are we in here?")
        if activeField != nil {
            print("active field was not nil")
            if (CGRectContainsPoint(aRect, activeField!.frame.origin) == false) {
                let scrollPoint:CGPoint = CGPointMake(0.0, activeField!.frame.origin.y - kbSize!.height)
                scrollView.setContentOffset(scrollPoint, animated: true)
            }

        }
    }

    func keyboardOffScreen(notification: NSNotification){
        print("keyboard off screen")
        let contentInsets:UIEdgeInsets = UIEdgeInsetsZero
        scrollView.contentInset = contentInsets
        scrollView.scrollIndicatorInsets = contentInsets
        self.scrollView.setContentOffset(CGPointMake(0, -self.view.frame.origin.y/2), animated: true)
    }

我的控制器扩展了文本视图委托。活动字段声明为可选字段。它设置如下:

    func textViewDidBeginEditing(textView: UITextView) {
        activeField = textView
        //other
    }

    func textViewDidEndEditing(commentTextView: UITextView) {
        activeField = nil
        //other
    }

0 个答案:

没有答案
相关问题