Exiting SwiftUI TextEditor

Viewed 154

Here is my code:

import SwiftUI

struct SendingView: View {

    //Only set when user taps "All Users"
    var TargetTopic: String
    //Only set when user selects specific people/groups
    var UUIDTargets: Array<String> = []
    //Body of the notification
    @State var NotificationMessage = "Body"

    @State var NotificationTitle = "Title"

    var body: some View {
      VStack {
        Image("NotificationExample")
          .resizable()
          .cornerRadius(10)
          .padding()
          .frame(height: 100)
        TextEditor(text: $NotificationTitle)
            .autocapitalization(.words)
            .frame(height: 100)
            .background(RoundedRectangle(cornerRadius:6).stroke(Color("Dominant"),lineWidth:2))
            .padding()
        TextEditor(text: $NotificationMessage)
            .autocapitalization(.words)
            .frame(height: 300)
            .background(RoundedRectangle(cornerRadius:6).stroke(Color("Dominant"),lineWidth:2))
            .padding()
        Spacer(minLength: 0)
      }
    }
}

How can I quickly exit the text view, because as you can see if you run the code, it quickly becomes hard to use and definitely not user friendly.

1 Answers

you can use @FocusState and add a button that sets it to nil:

struct ContentView: View {
    
    @State var NotificationMessage = "Body"
    @State var NotificationTitle = "Title"
    
    @FocusState var focusValue: Int?
    
    var body: some View {
        VStack {
            Image("NotificationExample")
                .resizable()
                .cornerRadius(10)
                .padding()
                .frame(height: 100)
            
            TextEditor(text: $NotificationTitle)
                .focused($focusValue, equals: 1) // here
                .autocapitalization(.words)
                .background(RoundedRectangle(cornerRadius:6).stroke(Color.blue,lineWidth:2))
                .frame(height: 100)
                .padding()
            
            TextEditor(text: $NotificationMessage)
                .focused($focusValue, equals: 2) // here
                .autocapitalization(.words)
                .frame(height: 300)
                .background(RoundedRectangle(cornerRadius:6).stroke(Color.blue,lineWidth:2))
                .padding()
            
            Button("Done") { focusValue = nil } // and here
            
            Spacer(minLength: 0)
        }
    }
}
Related