简体   繁体   中英

Set width of TextField in SwiftUI

When using TextField, I want to set it on a fixed width regardless to the shown text length, eg 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?

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM