Lars
Lars

Reputation: 475

SwiftUI: Expanding TextField size to font size before input

I'm having a problem with SwiftUI TextField. The cursor and text field size initially is very small, and on input it grows to the full size (in this case .largeTitle). I have made the background black so you can see what is happening to the actual field. Is there a way to set the size of the TextField so the cursor starts off the same size as the text? I have tried all the functions from the documentation with no luck... This is using Xcode 11 Beta 5. Thanks!

TextField("", text: input)
    .lineLimit(nil) // doesn't seem to work in Xcode 11 Beta 5
    .font(.largeTitle)
    .foregroundColor(.blue)
    .background(Color.black)

gif of problem

Upvotes: 4

Views: 6116

Answers (1)

kontiki
kontiki

Reputation: 40499

There's a bug where setting the style of textfield has no effect, unless the textfield has initial contents. Let's hope beta 6 fixes that. In the meantime, here's a workaround that works for me:

The textfield starts with a value, but resets immediately in the .onAppear closure, so you never actually see it:

struct ContentView: View {
    @State private var input = "x"

    var body: some View {
        TextField("", text: $input)
        .lineLimit(nil) // doesn't seem to work in Xcode 11 Beta 5
        .font(.largeTitle)
        .foregroundColor(.blue)
        .background(Color.black)
        .onAppear { self.input = "" }
    }
}

Upvotes: 2

Related Questions