Change background color of TextEditor in SwiftUI 4

DevTechie Inc
Jul 6, 2023

Change background color of TextEditor in SwiftUI 4

A text editor view allows us to display and edit multiline, scrollable text in our app’s user interface. By default, the text editor view styles the text using font, foregroundColor, and multilineTextAlignment modifiers but if you try to set background color for TextEditor, there is no straight forward way, well that statement was true until scrollContentBackground modifier was released with the launch of SwiftUI 4.

Using scrollContentBackground modifier, we can specify the visibility for the background of scrollable views. This includes List view as well as the TextEditor view.

Let’s create an example to see this in code.

struct DevTechieTextEditorBackground: View {
    
    @State private var inputText = ""
    
    var body: some View {
        NavigationStack {
            TextEditor(text: $inputText)
                .background(Color.orange)
                .scrollContentBackground(.hidden)
        }
    }
}

In this example, we are passing visibility parameter as hidden for scrollContentBackground. Other options are automatic, and visible.

Note that this is only supported for iOS 16+ and SwiftUI 4+. If you are looking to set background for iOS version below iOS 16, consider setting appearance property for UITextView as clear background color.

UITextView.appearance().backgroundColor = .clear

You can set this in onAppear modifier and reset the value back to nil, which is default for onDisappear.

.onAppear() {
   UITextView.appearance().backgroundColor = .clear
 }.onDisappear() {
   UITextView.appearance().backgroundColor = nil
 }