ScrollView内的TextView坚持键盘

时间:2015-03-13 23:20:35

标签: ios swift uiscrollview uitextview uikeyboard

我有一个UIScrollView内容。内容中有一个UITextView。当用户按下UITextView我希望UITextView粘在键盘上时。


在图像中:
整件事是UIScrollView
底部黑色区域是可见屏幕
红色区域是内容
蓝色区域为UITextView
绿色距离是内容与屏幕边界之间的动态余量。

我想计算用户可以看到的绿色距离以及用户可以看到的蓝色(UITextView)。如果用户半按UITextView,则UITextView仍应粘在键盘上。

    let userInfo = notification.userInfo!

    let keyboardEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue()
    let keyboardBeginFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as NSValue).CGRectValue()
    let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as UInt
    let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as Double

    let options = UIViewAnimationOptions(curve << 16)
    UIView.animateWithDuration(duration, delay: 0, options: options,
        animations: {

            var visibleGreen = ???
            var visibleBlue = ???
            var amountToSubtract = visibleGreen + visibleBlue


            var newFrame = (self.currentCardInstance?.newCommentCell.frame)!
            var kbFrameEnd = self.view.convertRect(keyboardEndFrame, toView: nil)
            var kbFrameBegin = self.view.convertRect(keyboardBeginFrame, toView: nil)
            newFrame.origin.y -= kbFrameBegin.origin.y - kbFrameEnd.origin.y + amountToSubtract

            self.currentCardInstance?.newCommentCell.frame = newFrame;
        },
        completion: nil
    )

1 个答案:

答案 0 :(得分:3)

以下是我解决它的方法:

var keyboardModifier: CGFloat = 0

func keyboardWillAppear(notification: NSNotification) {
    println("keyboardWillAppear")
    keyboardResize(notification: notification)
    scrollToBottom()
}

func keyboardWillDisappear(notification: NSNotification) {
    println("keyboardWillDisappear")
    keyboardResize(notification: notification)
}

func keyboardResize(#notification: NSNotification) {
    let userInfo = notification.userInfo!
    let keyboardEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue()
    let keyboardBeginFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as NSValue).CGRectValue()
    let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as UInt
    let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as Double
    let options = UIViewAnimationOptions(curve << 16)

    var newFrame = (self. currentCardInstance?.frame)!
    var kbFrameEnd = self.view.convertRect(keyboardEndFrame, toView: nil)
    var kbFrameBegin = self.view.convertRect(keyboardBeginFrame, toView: nil)

    keyboardModifier = kbFrameBegin.origin.y - kbFrameEnd.origin.y

    scrollView.frame.size.height -= keyboardModifier
}

func scrollToBottom() {
    var bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.size.height)
    scrollView.setContentOffset(bottomOffset, animated: false)
}