如何在SwiftUI中防止TextEditor滚动?

13

我试图创建一个的列表,作为SwiftUI应用程序的一部分。我希望单个编辑器不会滚动,因为它们组成了一个更大的滚动列表。但是,当我将TextEditors添加到列表中时,它们被压缩并且每个视图都变得可滚动。是否有修饰符/技巧可以让TextEditor始终适合其文本内容而无需滚动,以便我可以实现这一点?

下面是我尝试的最小示例:

struct ParentView: View {
    var items: [Item]

    var body: some View {
        List(items, id: \.id) { item in
            EditorView(item: item)
        }
    }
}

struct EditorView: View {
    @ObservedObject var item: Item

    var body: some View {
         TextEditor(text: $item.text)
    }
}

如果存在平台差异,请注意这是macOS的SwiftUI应用程序,而不是iOS应用程序。

编辑:如评论中所指出的,我尝试了这种方法在SwiftUI List中包含TextEditor的动态行高但似乎没有正确地工作 - 行仍然无法正确扩展。


这个回答解决了你的问题吗?https://dev59.com/g1IG5IYBdhLWcg3w2VbM? - Asperi
不好意思,我应该提到我尝试过那种方法,但似乎对我没用。 - merithayan
3个回答

5
为了解决这个问题,我最终使用了 .fixedSize(horizontal: false, vertical: true) 修改器来固定 TextEditor 的完整大小,这样就可以在列表中按预期使用 SwiftUI 中包含 TextEditor 的动态行高 解决方案了。

在iOS 14中,使用.fixedSize修饰符即可解决问题,无需使用ZStack和空的Text元素。虽然我没有将其放在ScrollView中。谢谢! - Clifton Labrum
1
很遗憾,在iOS15上它无法工作。 - Manuel Zompetta

2

iOS 15可以在init中使用UITextView.appearance().isScrollEnabled = false

init(para: EditorParagraph) {
      self._para = StateObject(wrappedValue: para)
      UITextView.appearance().backgroundColor = .clear
      UITextView.appearance().textDragInteraction?.isEnabled = false
      UITextView.appearance().isScrollEnabled  = false // here
}

var body: some View{
    ZStack {
        Text(para.content.isEmpty ? para.placeholder : para.content)
            .font(.system(size: para.fontSize, weight: para.content.isEmpty ? .thin : .regular))
            .lineSpacing(6)
            .opacity(para.content.isEmpty ? 1 : 0)
            .padding(.all, 8)
            .frame(maxWidth: .infinity, alignment: .leading)
    
        TextEditor(text: $para.content)
            .font(.system(size: para.fontSize, weight: .regular))
            .foregroundColor(.black)
            .lineSpacing(6)
    
    }
}

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接