TextEditor in SwiftUI — SerialCoder.dev

Solid greenish background with with text saying TextEditor in SwiftUI
TextEditor(text: .constant("Placeholder"))
@State private var text = ""

TextEditor basics

So, the most common way to get started with TextEditor should be similar to the following:

struct ContentView: View {    
@State private var text = ""

var body: some View {
TextEditor(text: $text)
}
}
TextEditor(text: $text)
.padding()
TextEditor(text: $text)
.padding(.vertical)
.padding(.horizontal, 20)
TextEditor(text: $text)
.padding()
.font(Font.custom("Noteworthy", size: 20, relativeTo: .body))
.foregroundColor(Color.blue)

TextEditor and background color

What seems not to be so straightforward is setting the background color of the text editor. Let’s start with the obvious way to do so:

TextEditor(text: $text)
...
.background(Color.green.opacity(0.25))
init() {
UITextView.appearance().backgroundColor = .clear
}

Reacting on text changes

Detecting changes on text and reacting on them is pretty easy with TextEditor. Let’s see that through a simple example.

@State private var text = ""
@State private var totalChars = 0
@State private var lastText = ""
var body: some View {
VStack {
TextEditor(text: $text)
.padding()
.background(Color.yellow.opacity(0.5))
.foregroundColor(Color.white)
.font(Font.custom("AvenirNext-Regular", size: 20, relativeTo: .body))
.frame(width: 300, height: 250)
.cornerRadius(25)

ProgressView("Chars: \(totalChars) / 150", value: Double(totalChars), total: 150)
.frame(width: 150)
.padding()
.accentColor(.yellow)
}
}
TextEditor(text: $text)
...
.onChange(of: text, perform: { text in

})
.onChange(of: text, perform: { text in
totalChars = text.count
})
.onChange(of: text, perform: { text in
...

if totalChars <= 150 {
lastText = text
} else {
self.text = lastText
}
})

An iOS & macOS app maker writing code in Swift. Author of countless programming tutorials. Content creator. https://serialcoder.dev

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store