Search code examples
swiftswiftui

Is there any way to set inputView for TextField in SwiftUI?


I want to set picker as my inputView for TextField, can I do it with SwiftUI only or I have to use UIKit components with help of framework integration?

Code example in UIKit:

textField.inputView = UIPickerView()

I want to do same, but with SwiftUI's TextField


Solution

  • As of Xcode 11.4, SwiftUI's TextField does not have an equivalent of the inputView property of UITextField.

    You can work around it by bridging a UIKit UITextField to SwiftUI, and by bridging a SwiftUI Picker to UIKit. You'll need to set the text field's inputViewController property rather than its inputView property.

    To bridge a UITextField to SwiftUI

    Use UIViewRepresentable to wrap the UITextField in a SwiftUI View. Since you create the UITextField, you can set its inputViewController property to a UIViewController that you create.

    To bridge a SwiftUI Picker into UIKit

    UseUIHostingController to wrap a SwiftUI Picker in a UIViewController. Set the text field's inputViewController to your UIHostingController instance.