Hi all,
I’m working on a UIKit app where I embed a SwiftUI TextField using
UIHostingController.
I’m using an ObservableObject model
to drive the textfield content:
class TextFieldModel: ObservableObject {
@Published var text: String
@Published var placeholder: String
@Published var isSecure: Bool
@Published var isFocused: Bool
init(pText: String, pPlaceholder: String, pIsSecure: Bool, pIsFocused: Bool) {
self.text = pText
self.placeholder = pPlaceholder
self.isSecure = pIsSecure
self.isFocused = pIsFocused
}
}
And my SwiftUI view:
struct TextFieldUI: View {
@ObservedObject var pModel: TextFieldModel
@FocusState private var pIsFocusedState: Bool
var body: some View {
TextField(pModel.placeholder, text: $pModel.text)
.focused($pIsFocusedState)
}
}
I embed it in UIKit like this:
let swiftUIContentView = TextFieldUI(pModel: model)
let hostingController = UIHostingController(rootView: swiftUIContentView)
addChild(hostingController)
view.addSubview(hostingController.view)
hostingController.didMove(toParent: self)
Question:
In UIKit, if I subclass UITextField, I can override insertText(_:) and choose not to call super, effectively preventing the textfield from updating when the user types.
Is there a SwiftUI equivalent to intercept and optionally prevent user input in a TextField, especially when it’s embedded inside UIKit?
What is the recommended approach in SwiftUI for this?