Paul
Paul

Reputation: 1431

How to detect newlines (return) from a multiline string text in TextEditor SwiftUI?

How would you take a multiline string input into TextEditor in SwiftUI and detect the breaks (newlines)?

edit: "detect the breaks" here refers to when a user presses the return button on a keyboard.

Upvotes: 1

Views: 304

Answers (1)

trianglejerry00
trianglejerry00

Reputation: 614

OnChange detects each time a value is entered and clears the last when it is newline. Is this the right implementation?

import SwiftUI

struct ContentView: View {
    @State private var text = ""
    
    var body: some View {
        VStack {
            TextEditor(text: $text)
                .onChange(of: text) { newValue in
                    print(newValue)
                    if newValue.contains("\n") {
                        text = String(text.dropLast())
                    }
                }
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Upvotes: 2

Related Questions