【发布时间】:2020-03-06 06:18:45
【问题描述】:
我正在努力为 SwiftUI 编写自己的 BetterTextField 视图,因为在几个方面都缺少内置的 TextField。也就是说,我想支持延迟绑定(仅在定位焦点时更新绑定值,而不是在每次按键后强制重绘)、程序化聚焦/响应器控制以及 SwiftUI 缺乏的 UIKit UITextField 的一些其他功能。
因此,我创建了一个自定义 UIViewRepresentable,并带有一个协调器作为 UITextFieldDelegate,并且工作正常。但是,为了与其他视图保持一致,我真的很想让我的自定义文本字段适应某些现有的 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 修饰符?
更一般地说,如何检查修饰符的存在并返回适当样式的自定义视图(例如 .bold() 可能会转换为属性文本)?
【问题讨论】:
标签: uikit uitextfield swiftui