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

nwsw7zdq  于 2023-05-28  发布在  Swift
关注(0)|答案(7)|浏览(149)

我使用Rectangle()在TextField上添加底部边框(SwiftUI)
但我想使用protocol TextFieldStyle作为TextField样式的底线,如RoundedBorderTextFieldStyle
如何在不使用Rectangle的情况下为TextField创建自定义样式?
https://developer.apple.com/documentation/swiftui/staticmember

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
ui7jx7zq

ui7jx7zq1#

分割器

可用于分隔其他内容的可视元素。
您可以设置colorheight

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

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

xqnpmsa82#

使用.overlay

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

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

w1e3prcc

w1e3prcc3#

要在不使用Rectangle的情况下实现TextField的自定义样式,而是遵循SwiftUI中的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())
omtl5h9j

omtl5h9j4#

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

我创建的第一个东西是一条水平线:

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和下面HorizontalLine的视图:

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

7cjasjjr5#

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

注:测试版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())
    }
}
ifsvaxew

ifsvaxew6#

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

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

lh80um4z7#

换个方式试试

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创建自定义 Package 器

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

相关问题