Post marked as solved
Post marked as solved with 12 replies, 8,573 views
I'm having trouble disabling keyboard avoidance for a SwiftUI view that is embedded in a UIHostingController. When the UITextField becomes first responder, the SwiftUI view jumps out of the way for the keyboard, and I want it to stay in place.
To test this out, set the ViewController as the rootViewController in a UIKit App Delegate.
import SwiftUI
struct ContentView: View {
var body: some View {
Text("I want this text to stay put.")
/* THIS DOESN'T WORK
.ignoresSafeArea(.keyboard)
*/
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let textField = UITextField(frame: CGRect(x: 10, y: 100, width: 200, height: 50))
textField.backgroundColor = .white
textField.placeholder = "Tap here!"
view.addSubview(textField)
let button = UIButton(type: .system, primaryAction: UIAction(title: "Dismiss Keyboard", handler: { _ in
textField.resignFirstResponder()
}))
button.frame = CGRect(x: 220, y: 100, width: 140, height: 50)
view.addSubview(button)
let hostingController = UIHostingController(rootView: ContentView())
hostingController.view.frame = CGRect(x: 10, y: UIScreen.main.bounds.size.height - 510, width: UIScreen.main.bounds.size.width - 20, height: 500)
view.addSubview(hostingController.view)
}
}