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

8

33

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
Neurotomy answered 13/7, 2019 at 11:32 Comment(0)
L
9

The solution of kontiki does not work with Beta 6, though. So I created a solution where I embed a TextField and a drawn bottom line in a new view. You can just copy the code and use it by writing TextFieldWithBottomLine(placeholder: "My placeholder") Used in a view it looks like:

Usage of TextView with bottom line

The first thing I create is a horizontal line:

import SwiftUI

struct HorizontalLineShape: Shape {

    func path(in rect: CGRect) -> Path {

        let fill = CGRect(x: 0, y: 0, width: rect.size.width, height: rect.size.height)
        var path = Path()
        path.addRoundedRect(in: fill, cornerSize: CGSize(width: 2, height: 2))

        return path
    }
}

struct HorizontalLine: View {
    private var color: Color? = nil
    private var height: CGFloat = 1.0

    init(color: Color, height: CGFloat = 1.0) {
        self.color = color
        self.height = height
    }

    var body: some View {
        HorizontalLineShape().fill(self.color!).frame(minWidth: 0, maxWidth: .infinity, minHeight: height, maxHeight: height)
    }
}

struct HorizontalLine_Previews: PreviewProvider {
    static var previews: some View {
        HorizontalLine(color: .black)
    }
}

Next I create a view that contains a TextField and the HorizontalLine below:

import SwiftUI

struct TextFieldWithBottomLine: View {
    @State var text: String = ""
    private var placeholder = ""
    private let lineThickness = CGFloat(2.0)

    init(placeholder: String) {
        self.placeholder = placeholder
    }

    var body: some View {
        VStack {
         TextField(placeholder, text: $text)
            HorizontalLine(color: .black)
        }.padding(.bottom, lineThickness)
    }
}

struct TextFieldWithBottomLine_Previews: PreviewProvider {
    static var previews: some View {
        TextFieldWithBottomLine(placeholder: "My placeholder")
    }
}

To see it in action I created a sample view:

import SwiftUI

struct SampleView: View {
    @State var text: String = ""
    @ObservedObject var model: LoginModel

    init() {
        self.model = LoginModel()
    }

    init(model: LoginModel) {
        self.model = model
    }

    var body: some View {
        TextFieldWithBottomLine(placeholder: "My placeholder").padding(24)
    }

    func initialActions() {

    }

    func reactOnButtonClick() {

    }
}

struct SampleView_Previews: PreviewProvider {
    static var previews: some View {
        SampleView()
    }
}
Log answered 14/11, 2019 at 11:11 Comment(1)
If no animation is going to be supported, we can make color and height to be private let.Pentecost
F
47

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()
        }
    }
}
Farra answered 26/2, 2020 at 9:14 Comment(1)
Just a note that you gain platform-suggested spacing by using .padding(.horizontal) (without specifying an explicit length)Dennett
A
32

Using .overlay

TextField("[email protected]", text: $email)
        .overlay(VStack{Divider().offset(x: 0, y: 15)})

enter image description here

the use of VStack is to ensure that the Divider is always horizontal.

Astrobiology answered 15/7, 2020 at 20:51 Comment(6)
Simply brilliant. Best answer.Helbonnas
why not use just .overlay(Divider(), alignment: .bottom)Incorruptible
What if I want to have different color divider?Ineffable
@NeerajJoshi did you try with the foreground color modifier?Astrobiology
@Astrobiology Yes I tried, it is not working.Ineffable
Baking in the y offset like this is not something you'd want to ship to production. It's going to cause issues once some of your users have larger accessibility text sizes enabled.Scarabaeid
C
11

To achieve a custom style for a TextField without using Rectangle and instead conforming to the TextFieldStyle protocol in SwiftUI

struct BottomLineTextFieldStyle: TextFieldStyle {
    func _body(configuration: TextField<Self._Label>) -> some View {
        VStack() {
            configuration
            Rectangle()
                .frame(height: 0.5, alignment: .bottom)
                .foregroundColor(Color.secondary)
        }
    }
}

Usage:

TextField("Name", text: $presenter.name).textFieldStyle(BottomLineTextFieldStyle())
Commie answered 12/12, 2019 at 10:19 Comment(0)
S
9

To define a custom style, you can use the code below. The Rectangle is used eventually, but inside the custom style, not in your view code. Is this what you want?

Note: Tested on Beta 3

To use your custom initialiser:

struct ContentView : View {
    @State private var username = ""

    var body: some View {
        VStack {

            TextField("Enter text", text: $username)
                .textFieldStyle(.myOwnStyle)

        }.frame(width:300)
    }
}

Your custom initialiser implementation:

public struct MyOwnTextFieldStyle: TextFieldStyle {
    public func _body(configuration: TextField<Self.Label>) -> some View {

        VStack() {
            configuration
                .border(Color.blue, width: 2)
                .foregroundColor(Color.yellow)
            Rectangle()
                .frame(height: 1.0, alignment: .bottom)
                .relativeWidth(1)
                .foregroundColor(Color.red)

        }
    }
}

extension StaticMember where Base : TextFieldStyle {
    public static var myOwnStyle: MyOwnTextFieldStyle.Member {
        StaticMember<MyOwnTextFieldStyle>(MyOwnTextFieldStyle())
    }
}
Sandhurst answered 13/7, 2019 at 15:19 Comment(2)
Yes, That's what I'm looking for. Thank you.Neurotomy
No more StaticMember in beta 6 any more. Any replacement?Patroclus
L
9

The solution of kontiki does not work with Beta 6, though. So I created a solution where I embed a TextField and a drawn bottom line in a new view. You can just copy the code and use it by writing TextFieldWithBottomLine(placeholder: "My placeholder") Used in a view it looks like:

Usage of TextView with bottom line

The first thing I create is a horizontal line:

import SwiftUI

struct HorizontalLineShape: Shape {

    func path(in rect: CGRect) -> Path {

        let fill = CGRect(x: 0, y: 0, width: rect.size.width, height: rect.size.height)
        var path = Path()
        path.addRoundedRect(in: fill, cornerSize: CGSize(width: 2, height: 2))

        return path
    }
}

struct HorizontalLine: View {
    private var color: Color? = nil
    private var height: CGFloat = 1.0

    init(color: Color, height: CGFloat = 1.0) {
        self.color = color
        self.height = height
    }

    var body: some View {
        HorizontalLineShape().fill(self.color!).frame(minWidth: 0, maxWidth: .infinity, minHeight: height, maxHeight: height)
    }
}

struct HorizontalLine_Previews: PreviewProvider {
    static var previews: some View {
        HorizontalLine(color: .black)
    }
}

Next I create a view that contains a TextField and the HorizontalLine below:

import SwiftUI

struct TextFieldWithBottomLine: View {
    @State var text: String = ""
    private var placeholder = ""
    private let lineThickness = CGFloat(2.0)

    init(placeholder: String) {
        self.placeholder = placeholder
    }

    var body: some View {
        VStack {
         TextField(placeholder, text: $text)
            HorizontalLine(color: .black)
        }.padding(.bottom, lineThickness)
    }
}

struct TextFieldWithBottomLine_Previews: PreviewProvider {
    static var previews: some View {
        TextFieldWithBottomLine(placeholder: "My placeholder")
    }
}

To see it in action I created a sample view:

import SwiftUI

struct SampleView: View {
    @State var text: String = ""
    @ObservedObject var model: LoginModel

    init() {
        self.model = LoginModel()
    }

    init(model: LoginModel) {
        self.model = model
    }

    var body: some View {
        TextFieldWithBottomLine(placeholder: "My placeholder").padding(24)
    }

    func initialActions() {

    }

    func reactOnButtonClick() {

    }
}

struct SampleView_Previews: PreviewProvider {
    static var previews: some View {
        SampleView()
    }
}
Log answered 14/11, 2019 at 11:11 Comment(1)
If no animation is going to be supported, we can make color and height to be private let.Pentecost
D
2

My solution is to add a divider under the textfield:

private let textFieldLength:CGFloat = 200
var body: some View {
     VStack {
         TextField("placeHolder", text: .constant("")).frame(width: textFieldLength, height: 30, alignment: .center)
         Divider().frame(width: textFieldLength, height: 2, alignment: .center)
     }
}

or use overlay

 TextField("", text: .constant(""))
  .frame(width: textFieldLength, height: 30, alignment: .center)
  .multilineTextAlignment(.leading)
  .overlay(Divider().frame(width: textFieldLength, height: 2, alignment: .center), alignment: .bottom)
Drachma answered 10/2, 2020 at 0:10 Comment(2)
I think that overlay's solutions are more cleaner than othersAstrobiology
I love the simplicity of the first snippet. Excellent.Architrave
B
0

Try it another way

struct ContentView: View {
    @State var name: String = ""
    var body: some View {
        VStack {
            // change frame as per requirement
           TextField("Please enter text", text: $name)
            .frame(width: 300, height: 30, alignment: .center)
            .background(Color.gray.opacity(0.2))
            LineView().frame(width: 300, height: 1.0, alignment: .center)
        }
    }
}

LineView : Create custom wrappers for a UIView

struct LineView: UIViewRepresentable {

    typealias UIViewType = UIView
    func makeUIView(context: UIViewRepresentableContext<LineView>) -> UIView {
        let view = UIView()
        view.backgroundColor = UIColor.lightGray
        return view
    }

    func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<LineView>) {
    }
}
Berndt answered 13/12, 2019 at 10:6 Comment(1)
creating a UIViewRepresentable for something that can be created with Divider/Overlay/Rectangle wastes time and code.Halliday
H
-1

Another solution is to use a ZStack with vertical alignment set to bottom, and a rectangle of height:1. For example:

ZStack(alignment: Alignment(horizontal: .center, vertical: .bottom)) {
  Text("This is my text")
    .padding()
  Rectangle()
    .fill(Color(.systemGray4)
    .frame(height:1)
}

I did something like this when I wanted to make custom list items...

Houle answered 10/7 at 20:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.