Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set width of TextField in SwiftUI

When using TextField, I want to set it on a fixed width regardless to the shown text length, e.g. field width for "123456789", even if the content is only "1".

TextField("0", text: $username)
    .textFieldStyle(RoundedBorderTextFieldStyle())
    .fixedSize(horizontal: true, vertical: false)
    .frame(width: 120)

I didn't find anything to set the width. Using frame only affect the surrounding frame, but I want to set the width of the TextField itself. So the visible width should be wider than the content of it. Any idea?

like image 597
Peter Silie Avatar asked Nov 18 '25 19:11

Peter Silie


1 Answers

Just move the .frame() modifier before applying the .textFieldStyle() modifier.

import SwiftUI

struct ContentView: View {
    @State private var username = ""
    
    var body: some View {
        TextField("0", text: $username)
            .frame(width: 120)
            .textFieldStyle(RoundedBorderTextFieldStyle())
            .fixedSize(horizontal: true, vertical: false)
    }
}

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

There you go!

like image 121
Alexander Thoren Avatar answered Nov 21 '25 09:11

Alexander Thoren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!