如何在SwiftUI中修改TextField的指示器颜色?
修改SwiftUI TextField指示器颜色的代码实现
问题说明
想要修改SwiftUI中TextField的底部指示器颜色(默认橙色条)为蓝色,不想通过修改Xcode全局accent color实现,希望用代码单独设置。
示例代码:
TextField("What's in your mind?", text: $userInput)
解决方案
方法一:SwiftUI原生修饰符(推荐)
iOS 14+:使用accentColor修饰符
直接给目标TextField添加accentColor修饰符,仅对当前TextField生效,不影响全局样式:
TextField("What's in your mind?", text: $userInput) .accentColor(.blue)
iOS 15+:使用tint修饰符
iOS 15及以上版本可使用更贴合系统设计规范的tint修饰符,效果与accentColor一致:
TextField("What's in your mind?", text: $userInput) .tint(.blue)
方法二:兼容iOS 13的自定义实现
如果需要兼容iOS 13,可通过封装UIViewRepresentable自定义UITextField的指示器样式:
struct CustomTextField: UIViewRepresentable { let placeholder: String @Binding var text: String let tintColor: UIColor func makeUIView(context: Context) -> UITextField { let textField = UITextField() textField.placeholder = placeholder textField.delegate = context.coordinator textField.tintColor = tintColor // 自定义底部指示器 let bottomLine = CALayer() bottomLine.frame = CGRect(x: 0, y: textField.frame.height - 1, width: textField.frame.width, height: 1) bottomLine.backgroundColor = tintColor.cgColor textField.borderStyle = .none textField.layer.addSublayer(bottomLine) return textField } func updateUIView(_ uiView: UITextField, context: Context) { uiView.text = text } func makeCoordinator() -> Coordinator { Coordinator(self) } class Coordinator: NSObject, UITextFieldDelegate { var parent: CustomTextField init(_ parent: CustomTextField) { self.parent = parent } func textFieldDidChangeSelection(_ textField: UITextField) { parent.text = textField.text ?? "" } } } // 使用方式 CustomTextField(placeholder: "What's in your mind?", text: $userInput, tintColor: .blue)
内容的提问来源于stack exchange,提问作者Legolas Wang
相关产品推荐
相关产品推荐

