ios - 当文本下降到 Swift 中的键盘级别时,如何在我的 TextView 中实现自动滚动?

标签 ios swift

我知道当内容(文本)超过 TextView 的默认高度时会自动滚动,但我希望 TextView 是全屏的,当内容到达键盘级别时, TextView 应该滚动自动地。我已经给出了一个 GIF 以帮助读者更好地理解。

Notes on IOS

class StartStoryPopUp: UIViewController, UITextViewDelegate {
    // Setup text view
    func setupTextView() {

        textViewOne.textColor = .black
        textViewOne.backgroundColor = baseColor
        // Add some padding to the text insde the text view
        textViewOne.textContainerInset = UIEdgeInsets(top: 15, left: 10, bottom: 15, right: 10)
        textViewOne.font = UIFont(name: "PatrickHand-Regular", size: 25)
        textViewOne.layer.cornerRadius = 25

        popUp.addSubview(textViewOne)
        addTextViewConstraints()
    }

    // Add the constraints to the 'start story' text view
    func addTextViewConstraints() {

        textViewOne.translatesAutoresizingMaskIntoConstraints = false
        textViewOne.leadingAnchor.constraint(equalTo: popUp.leadingAnchor, constant: 3).isActive = true
        textViewOne.trailingAnchor.constraint(equalTo: popUp.trailingAnchor, constant: -3).isActive = true
        textViewOne.topAnchor.constraint(equalTo: popUp.topAnchor, constant: 3).isActive = true
        textViewOne.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -30).isActive = true
    }
}

最佳答案

swift 5

也许这条线对你有用。

您应该在 textViewDidChange 函数中设置 contentOffSet,如下所示:

func textViewDidChange(_ textView: UITextView) {

    let line = textView.caretRect(for: (textView.selectedTextRange?.start)!)
    let overFlow = line.origin.y + line.size.height - (textView.contentOffset.y + textView.bounds.size.height - textView.contentInset.bottom - textView.contentInset.top)

    if 0 < overFlow {

        var offSet = textView.contentOffset
        offSet.y += (overFlow + 7)

        UIView.animate(withDuration: 0.3, animations: {
            textView.setContentOffset(offSet, animated: true)
        })
    }
}

关于ios - 当文本下降到 Swift 中的键盘级别时,如何在我的 TextView 中实现自动滚动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56747257/

相关文章:

ios - 从解析本地数据存储检索信息

c++ - 在 SWIFT 中使用 C++ FFT 代码

ios - 如何在 SwiftUI 中自定义文本

ios - Xcode: EXC_BREAKPOINT (EXC_ARM_BREAKPOINT, subcode=0xe7ffdefe)

ios - 从 fourthviewcontroller objective-c 中的 firstviewcontroller 访问字符串

ios - 如何使用日期格式获取小时

ios - 在iphone sdk中改变图像的颜色

ios - 将变量放在 AppDelegate 中是 Swift 中静态变量的解决方法吗?

ios - 搜索包含特定日期属性的核心数据数组的索引

ios - 注释引脚颜色和类型