ios - 在 SwiftUI 的 UITextView 中禁用向上滚动

标签 ios swift swiftui uikit

我在项目中使用 UITextView,我需要它只能向下滚动(不能向上滚动)。有没有办法可以相对容易地做到这一点?如果不是,我可能会继承 UIScrollView 或一些奇怪的东西,但我真的不想这样做。
这是我的基本 UIViewRepresentable 结构

struct TextView: UIViewRepresentable {
    
    typealias UIViewType = UITextView
    var configuration = { (view: UIViewType) in }
    
    func makeUIView(context: UIViewRepresentableContext<Self>) -> UIViewType {
        let view = UIViewType()
        view.isEditable = false
        
        return view
    }
    
    func updateUIView(_ uiView: UIViewType, context: UIViewRepresentableContext<Self>) {
        configuration(uiView)
    }
}
谢谢!

最佳答案

可以通过 UITextView 的简单子(monad)类来完成处理平移手势激活。
使用 Xcode 12 测试
demo

class BottomScrollTextView: UITextView {
    override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        guard let gr = gestureRecognizer as? UIPanGestureRecognizer else { return true }

        return gr.translation(in: self).y < 0    // << allow only to down
    }

    private var _contentOffset = CGPoint.zero
    override var contentOffset: CGPoint {
        get { super.contentOffset }
        set {
            if newValue.y > super.contentOffset.y || self.isDecelerating {
                super.contentOffset = newValue
            }
        }
    }
}

struct TextView: UIViewRepresentable {

    typealias UIViewType = UITextView
    var configuration = { (view: UIViewType) in }

    func makeUIView(context: UIViewRepresentableContext<Self>) -> UIViewType {
        let view = BottomScrollTextView()   // << here !!

        // ... other code

关于ios - 在 SwiftUI 的 UITextView 中禁用向上滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63198668/

相关文章:

ios - block 内的强弱。我该如何处理这个问题?

ios - Swift UIImage 转换为 PDF

ios - 默认情况下启用推文按钮当文本在 Twitter 共享扩展中超过 280 个字符时

swiftui - 我无法在测试的拆卸阶段删除我的应用程序

ios - SwiftUI如何设置下划线与文字的间距?

ios - 在运行时切换到FlatUIKit分段控件

swift - CGPath 的 PhysicsEditor 多边形路径

ios - 图表 LineChartView 框架获取 : fatal error: unexpectedly found nil while unwrapping an Optional value

swiftui - Swift ScrollView 再次置顶

iphone - 何时 Split View和 Controller