iosswiftswiftuitext-editor

Add horizontal padding to TextEditor but prevent it from shifting scrollbar inside as a result


I'm using a TextEditor that I'd like to include horizontal padding for, so that the text doesn't stick to either edge. However, the problem is if I include it, and the text within is scrollable, then the scrollbar is not positioned to the far-right, but has instead been moved inside by the padding amount.

        TextEditor(text: $text)
         .background(Color.white)
         .foregroundColor(Color.black)
         .frame(maxWidth: .infinity, maxHeight: .infinity)
         .customFont(.body)
         .lineSpacing(8)
         .padding(.leading)
         .padding(.trailing)

enter image description here


Solution

  • You added padding to external frame, but need to indent internal text container. The possible solution (as TextEditor is actually UITextView) to use appearance. So the solution would be to add the following in parent view of TextEditor

    init() {
        UITextView.appearance().textContainerInset = 
             UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 12)   // << !!
    }
    
    // ... other code
    
        TextEditor(text: $text)
         .background(Color.white)
         .foregroundColor(Color.black)
         .frame(maxWidth: .infinity, maxHeight: .infinity)
         .customFont(.body)
         .lineSpacing(8)
    

    Tested with Xcode 12 / iOS 14