Search code examples
macosswiftuifocus

SwiftUI on MacOS App - strange Focus behavior


I have this little example app, that works as expected.
The Textfields an the YellowTextfield get the focus in the expected order.

If I add a .cornerRadius(5.0) th the Textfield of YellowTextfield, the focusorder changes.
Now the YellowTextfield gets the focus on start.

Why does this happen and how can I prevent this?

struct TestFocusOrder: View {
  @State var name = ""
  @State var age = ""
  @State var city = ""
  @State var job = ""

  var eyeColors = ["Red", "Green", "Blue", "Tartan"]
  @State private var eyeColor = ""

  var body: some View {
    VStack{
      TextField("Name", text: $name)
      YellowTextField(title: "yellow field", text: $city)
      TextField("age", text: $age)
      Picker("eye color", selection: $eyeColor) {
        ForEach(eyeColors, id: \.self) {
          Text($0)
        }
      }
      Text("\(name) age:\(age) eye color:\(eyeColor)").font(.footnote)
    } .frame(width: 400, height: 400, alignment: .center)
  }
}

struct YellowTextField: View {
  var title: String
  @Binding var text : String

  var body: some View {
    TextField(title, text: $text)
      //.cornerRadius(5.0).   // <== Uncomment this, then the focus order changes
  }
}


Solution

  • Unfortunately .cornerRadius(5.0) does not round corners of TextField in MacOs like it could in iOS

    Try this:

    TextField(title, text: $text)
    .textFieldStyle(RoundedBorderTextFieldStyle()) // <-- rounded
    

    For greater customization something like:

    TextField(title, text: $text)
    .padding()
    .overlay(
        RoundedRectangle(cornerRadius: 5)
        .stroke(Color.blue, lineWidth: 1)
    )