我正在努力为 SwiftUI 编写自己的 BetterTextField
View ,因为内置的 TextField
在几个方面都缺乏。也就是说,我想支持延迟绑定(bind)(仅在定位焦点时更新绑定(bind)值,而不是在每次按键后强制重绘)、编程式焦点/响应器控制以及 UIKit 的 UITextField
的一些其他功能,SwiftUI缺乏。
因此,我创建了一个自定义 UIViewRepresentable
,并将协调器作为 UITextFieldDelegate
并且工作正常。但是,为了与其他 View 保持一致,我真的想让我的自定义文本字段适应某些现有的 SwiftUI 修饰符。
例如:
// Here's my content view
struct ContentView: View {
var body: some View {
BetterTextField("Username", text: $username)
// I want to adapt the view to this modifier
.textFieldStyle(RoundedBorderTextFieldStyle())
}
}
// Here's my (simplified) custom text field view
struct BetterTextField: UIViewRepresentable {
var title: String
@Binding var text: String
init(_ title: String, text: Binding<String>) {
self.title = title
self._text = text
}
func makeUIView(context: Context) -> UITextField {
let textField = UITextField()
textField.placeholder = title
return textField
}
func updateUIView(_ view: UITextField, context: Context) {
view.text = text
// How can I check for the .textFieldStyle() modifier here and set the corresponding UIKit style accordingly?
view.borderStyle = .roundedRect
}
}
正如评论所说,如何调整 UITextField
的 borderStyle
属性以匹配 View 修饰符?
更一般地说,如何检查修饰符是否存在并返回适当样式的自定义 View (例如 .bold()
转换为属性文本,也许)?
最佳答案
View
修饰符只是再次返回某些 View
的函数,因此您可以实现对任何修饰符的支持,符合您认为适合自定义类型的任何协议(protocol)。您的控件在每个已实现的修饰符上的行为方式取决于您。
下面是对 textFieldStyle
修饰符的简单演示支持,它使您的 ContentView
根据添加或删除的圆形矩形样式修饰符按预期渲染 BetterTextField
.
struct BetterTextField: UIViewRepresentable {
var title: String
@Binding var text: String
private let textField = UITextField()
init(_ title: String, text: Binding<String>) {
self.title = title
self._text = text
}
func makeUIView(context: Context) -> UITextField {
textField.placeholder = title
return textField
}
func updateUIView(_ view: UITextField, context: Context) {
view.text = text
}
}
extension BetterTextField {
func textFieldStyle<S>(_ style: S) -> some View where S : TextFieldStyle {
if style is RoundedBorderTextFieldStyle {
self.textField.borderStyle = .roundedRect
}
return self
}
}
关于uikit - 使自定义 SwiftUI View 适应内置修饰符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60558564/