4

I am struggling to figure out how to make a TextView in a SwiftUI view become the first responder. I have an AddTaskView like this

struct AddTaskView: View {
  @State var text:String = ""
  @State var priority: String = Priority.priority1.rawValue
  @Binding var tasks:[Task]
  @Binding var isAdding:Bool
  var updateTasks:() -> Void
  var body: some View {
      VStack(alignment: .trailing) {
          PriorityPicker(selected: $priority, filter: false)

          // I want this TextView to become the first Responder
          TextView(placeholderText: "Enter Task", text: $text).frame(numLines: 3)

          Button("Add") {
              self.tasks.append(Task(id: UUID(), name: self.text, priorityString: self.priority))
              self.updateTasks()
              withAnimation(.default) {
                  self.isAdding = false
              }
          }.disabled(text.isEmpty)
          Spacer()
      }
      .frame(height: 170)
  }
}

And I would like the TextView to become the first responder when the View appears. I have been trying something like this on the TextView

        .onAppear{
            UIApplication.shared.sendAction(#selector(UIResponder.becomeFirstResponder), to: Any?, from: Any?, for: UIEvent?)
        }

but I do not know what to enter for the two Any? and for the UIEvent?

Stewart Lynch
  • 875
  • 9
  • 26
  • Have you looked at this one [How to make TextField become first responder?](https://stackoverflow.com/questions/56507839/how-to-make-textfield-become-first-responder) – Asperi Nov 09 '19 at 19:25
  • I didn't find that one so thanks for pointing it out. – Stewart Lynch Nov 09 '19 at 19:31

0 Answers0