ios 如何更改SwiftUI TextField样式后点击它?

8zzbczxx  于 2023-07-01  发布在  iOS
关注(0)|答案(2)|浏览(184)

我这样修改了TextField样式:

TextField("Test", text: $name).textFieldStyle(CustomTextFieldStyle())

现在,我想它改变风格时,用户点击它。
我的CustomTextFieldStyle定义为:

public struct CustomTextFieldStyle : TextFieldStyle {
    public func _body(configuration: TextField<Self._Label>) -> some View {
        configuration
            .font(.callout)
            .padding(10)
            .background(
                RoundedRectangle(cornerRadius: 4)
                    .strokeBorder(SBGreen, lineWidth: 2))
    }
}
jhiyze9q

jhiyze9q1#

TextField("Test", text: $name).textFieldStyle(tapflag ? CustomTextFieldStyle1() : CustomTextStyle2())

你有自己的文本样式的例子吗?请分享!
更新
你最好在你的样式中使用一些参数,并将其绑定到“父”视图

import SwiftUI

struct ContentView: View {

    @State private var email = ""
    @State private var editing = false
    var body: some View {
        TextField("Email", text: self.$email, onEditingChanged: { edit in
            self.editing = edit
        })
            .textFieldStyle(MyTextFieldStyle(focused: $editing)).font(.title).border(Color.blue)
    }
}

struct MyTextFieldStyle: TextFieldStyle {
    @Binding var focused: Bool
    func _body(configuration: TextField<Self._Label>) -> some View {
        configuration
        .padding(10)
        .background(
            RoundedRectangle(cornerRadius: 10, style: .continuous)
                .stroke(focused ? Color.red : Color.gray, lineWidth: 3)
        ).padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

结果类似于x1c 0d1x

a6b3iqyw

a6b3iqyw2#

实际变量为

import SwiftUI

struct CustomInput: View {
   @Binding var input: String
   @FocusState private var editing

   let width: CGFloat
   let placeholder: String

  var body: some View {
      TextField(
          "",
          text: $input,
          prompt: Text(placeholder)
      )
      .frame(width: width, height: 37)
      .textFieldStyle(BorderedStyle(focused: editing))
      .focused($editing)
      .multilineTextAlignment(.center)
      .keyboardType(.numberPad)
    }
 }

struct BorderedStyle: TextFieldStyle {
  var focused: Bool

  func _body(configuration: TextField<Self._Label>) -> some View {
      configuration
      .padding(10)
      .background(
          Rectangle()
              .stroke(
                  focused ? Color.red : Color.grey, lineWidth: 2
              )
      )
  }}

相关问题