You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中关闭PlacePicker Sheet后如何隐藏键盘?

解决方案

可以在PlacePicker类中添加逻辑实现选择地点后自动隐藏键盘,具体修改如下:

修改PlacePicker的协调器代码

在协调器的didAutocompleteWith(选择地点完成)和wasCancelled(取消选择)方法中,添加隐藏键盘的代码,确保无论哪种关闭Sheet的方式都能收起键盘:

class GooglePlacesCoordinator: NSObject, UINavigationControllerDelegate, GMSAutocompleteViewControllerDelegate {

    var parent: PlacePicker

    init(_ parent: PlacePicker) {
        self.parent = parent
    }

    func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
        DispatchQueue.main.async {
            print(place.description.description as Any)
            self.parent.address = place.formattedAddress ?? "adresa gresita"
            self.parent.latitude = place.coordinate.latitude
            self.parent.longitude = place.coordinate.longitude
            
            // 新增:隐藏键盘
            UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
            
            self.parent.presentationMode.wrappedValue.dismiss()
        }
    }

    func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
        print("Error: ", error.localizedDescription)
    }

    func wasCancelled(_ viewController: GMSAutocompleteViewController) {
        // 新增:取消时也隐藏键盘
        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
        parent.presentationMode.wrappedValue.dismiss()
    }
}

修复调用代码的参数问题

你的调用代码中,PlacePicker初始化时缺少绑定参数,需要补充完整,否则会编译报错:

.sheet(isPresented: $openPlacePicker) {
    PlacePicker(address: $address, latitude: .constant(0), longitude: .constant(0))
}

另外,TextField的占位符写法可以优化,避免不必要的字符串插值:

TextField(address, text: $addressString)

原理说明

UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) 会遍历当前所有活跃的UIResponder,让之前获取焦点的TextField(第一响应者)放弃焦点,从而自动隐藏键盘。这种方式不需要直接持有TextField的引用,适合在Sheet组件中操作主界面的键盘状态。

内容的提问来源于stack exchange,提问作者user20810748

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 17:15:34