[swift]在滚动视图内的 TextView 坚持键盘

发布时间: 2015/6/19 3:32:29
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有 UIScrollView 和在它里面的内容。里面内容有 UITextView 。当用户按下 UITextView 我想要 UITextView 坚持键盘。


在图像:
整件事是UIScrollView
底部的黑色区域是可见的屏幕
红色区域是内容
蓝色区域是UITextView
绿色的距离是内容和绑定的屏幕之间的动态保证金。

我想要计算,用户可以看到同时有蓝色的绿色的距离 ( UITextView ),用户可以看到。如果用户一半刷卡 UITextViewUITextView 仍应坚持使用键盘。

    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:

这里是怎么解决的:

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)
}
官方微信
官方QQ群
31647020