如何在TextField(SwiftUI)上添加底线

时间:2019-07-13 11:32:27

标签: swift textfield swiftui

我使用Rectangle()在TextField(SwiftUI)上添加底部边框

但是我想使用protocol TextFieldStyle作为诸如RoundedBorderTextFieldStyle之类的TextField Style的底线

如何在不使用Rectangle的情况下为TextField创建自定义样式?

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

7 个答案:

答案 0 :(得分:20)

除法器

可用于分隔其他内容的视觉元素。

您可以设置colorheight

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()
        }
    }
}

答案 1 :(得分:5)

要定义自定义样式,可以使用以下代码。最终将使用Rectangle,但在自定义样式中,而不是在视图代码中使用。这就是你想要的吗?

注意:已在Beta 3上进行了测试

要使用自定义初始化程序,请执行以下操作:

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

    var body: some View {
        VStack {

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

        }.frame(width:300)
    }
}

您的自定义初始化程序实现

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())
    }
}

答案 2 :(得分:3)

kontiki的解决方案不适用于 Beta 6 。 因此,我创建了一个解决方案,其中将TextField和绘制的底线嵌入到新视图中。您只需复制代码并通过编写TextFieldWithBottomLine(placeholder: "My placeholder")在视图中使用它,就可以使用它:

Usage of TextView with bottom 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)
    }
}

接下来,我创建一个视图,其中包含一个TextField和下面的Horizo​​ntalLine:

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")
    }
}

要查看实际效果,我创建了一个示例视图:

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()
    }
}

答案 3 :(得分:3)

使用.overlay

TextField("mail@example.com", text: $email)
        .overlay(VStack{Divider().offset(x: 0, y: 15)})

enter image description here

使用VStack是为了确保Divider始终是水平的。

答案 4 :(得分:1)

我的解决方案是在文本字段下添加一个分隔符:

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)
     }
}

或使用叠加层

 TextField("", text: .constant(""))
  .frame(width: textFieldLength, height: 30, alignment: .center)
  .multilineTextAlignment(.leading)
  .overlay(Divider().frame(width: textFieldLength, height: 2, alignment: .center), alignment: .bottom)

答案 5 :(得分:0)

符合TextFieldStyle协议

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

用法:

TextField("Name", text: $presenter.name).textFieldStyle(BottomLineTextFieldStyle())

答案 6 :(得分:0)

以其他方式尝试

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 :为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>) {
    }
}