I am endeavouring to write my own BetterTextField view for SwiftUI, since the built-in TextField is lacking in several areas. Namely, I want to support delayed binding (updating the bound value only on locusing focus, instead of forcing redraws after every keypress), programmatic focusing/responder control, and a few other features of UIKit's UITextField that SwiftUI lacks.
So I've created a custom UIViewRepresentable with a coordinator as the UITextFieldDelegate and that's working fine. However, for parity with other views, I'd really like to have my custom text field adapt to certain existing SwiftUI modifiers.
For example:
// 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
}
}
As the comment says, how can I adapt the borderStyle property of my UITextField to match the View modifier?
And more generally, how does one check for the presence of modifiers and return the appropriately-styled custom view (such as .bold() translating to attributed text, perhaps)?
