iOS开发:键盘弹出时如何将含UIPickerView的整体视图向上移动?
问题根因
你之前修改页面偏移没有生效,是因为inputView和inputAccessoryView属于系统独立管理的输入视图层级,不在当前控制器的视图子层级中,所以修改当前页面的偏移不会影响输入视图的位置。
解决方案
方案1:合并输入视图+监听键盘通知(适用需要搜索栏唤起键盘的场景)
将工具栏和选择器放到同一个自定义容器视图中作为整体输入视图,再监听键盘弹出/收起通知,统一调整容器的位置即可实现同步移动:
步骤1:合并输入视图
替换你原有输入视图绑定逻辑:
// 1. 创建自定义容器视图 let totalHeight: CGFloat = 44 + 216 // 工具栏高度 + 选择器高度 let customInputView = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: totalHeight)) customInputView.backgroundColor = UIColor.black.withAlphaComponent(0.82) // 2. 将工具栏、选择器添加到同一容器 toolBar.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 44) picker.frame = CGRect(x: 0, y: 44, width: screenWidth, height: 216) customInputView.addSubview(toolBar) customInputView.addSubview(picker) // 3. 统一绑定为文本框的输入视图,清空原有附属视图 tfCountry.inputView = customInputView tfCountry.inputAccessoryView = nil
步骤2:添加键盘监听
在控制器中添加键盘状态监听,动态调整输入容器位置:
override func viewDidLoad() { super.viewDidLoad() // 添加键盘通知监听 NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) } // 键盘弹出时向上平移输入容器 @objc func keyboardWillShow(_ notification: Notification) { guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect, let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else { return } let keyboardHeight = keyboardFrame.height UIView.animate(withDuration: duration) { self.tfCountry.inputView?.transform = CGAffineTransform(translationX: 0, y: -keyboardHeight) } } // 键盘收起时恢复输入容器位置 @objc func keyboardWillHide(_ notification: Notification) { guard let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else { return } UIView.animate(withDuration: duration) { self.tfCountry.inputView?.transform = .identity } } // 移除通知避免内存泄漏 deinit { NotificationCenter.default.removeObserver(self) }
方案2:禁用搜索栏自带键盘(适用仅本地筛选不需要键盘输入的场景)
如果你的搜索功能仅需要对选择器已有数据源做本地筛选,不需要唤起系统键盘,可以直接给搜索栏设置空输入视图,从根源避免键盘弹出的问题:
// 添加到搜索栏初始化逻辑中 searchBar.inputView = UIView()
后续直接在UISearchBarDelegate的文本变化回调中筛选选择器数据源,刷新选择器展示即可。
内容的提问来源于stack exchange,提问作者Sabaz Shereef
相关产品推荐
相关产品推荐

