How can I add a bottom line on TextField (SwiftUI)

Shawn Baek picture Shawn Baek · Jul 13, 2019 · Viewed 10.3k times · Source

I use Rectangle() to adding a bottom border on TextField (SwiftUI)

But I want to use protocol TextFieldStyle for a bottom line on TextField Style like an RoundedBorderTextFieldStyle

How can I make a custom style for TextField without using Rectangle?

https://developer.apple.com/documentation/swiftui/staticmember

enter image description here

struct ContentView : View {
    @State private var username = "Text Hellow"
    var body: some View {
        VStack() {
            TextField($username)
                .foregroundColor(Color.yellow)
            Rectangle()
                .frame(height: 1.0, alignment: .bottom)
                .relativeWidth(1)
                .foregroundColor(Color.red)

        }
        .padding()
    }

    func editChanged() {

    }
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
#endif

Answer

Harshal Valanda picture Harshal Valanda · Feb 26, 2020

Divider

A visual element that can be used to separate other content.

You can set color and height

Divider()
 .frame(height: 1)
 .padding(.horizontal, 30)
 .background(Color.red)

enter image description here

struct LoginField: View {

    @State private var email: String = ""
    @State private var password: String = ""

    var body: some View {
        VStack {
            TextField("Email", text: $email)
                .padding(.horizontal, 30).padding(.top, 20)
            Divider()
                .padding(.horizontal, 30)
            TextField("Password", text: $password)
                .padding(.horizontal, 30).padding(.top, 20)
            Divider()
                .padding(.horizontal, 30)
            Spacer()
        }
    }
}