Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent TextEditor from scrolling in SwiftUI?

I am trying to create a list of TextEditors as part of a SwiftUI app. I want the individual editors not to scroll, as they make up a larger scrolling list. However, when I add the TextEditors to the list, they compress down and each view becomes individually scrollable. Is there a modifier / trick to getting the TextEditor to always fit its text content without scrolling, so I can achieve this?

A minimal example of what I'm trying to do is below:

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)
    }
}

This is in a macOS SwiftUI app, not an iOS one, in case there is any platform differences.

Edit: As pointed out in the comments I tried this approach Dynamic row hight containing TextEditor inside a List in SwiftUI but it didn't seem to work correctly - the rows still didn't expand properly.

like image 418
merithayan Avatar asked Aug 03 '20 18:08

merithayan


3 Answers

To solve this problem, I ended up using the .fixedSize(horizontal: false, vertical: true) modifier to fix the TextEditor to its full size, which then allowed the solution in Dynamic row hight containing TextEditor inside a List in SwiftUI to work as expected within the list.

like image 139
merithayan Avatar answered Oct 20 '22 00:10

merithayan


iOS 15 can use in 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)
    
    }
}
like image 27
XavierZzz Avatar answered Oct 20 '22 01:10

XavierZzz


Will be fixed in macOS 13.0 with a scrollDisabled(_disabled: Bool) function. Seems to be a major hole in TextEditor

https://developer.apple.com/documentation/swiftui/list/scrolldisabled(_:)

like image 36
Zach Hall Avatar answered Oct 20 '22 00:10

Zach Hall