咨询:iOS中移除键盘隐藏按钮,仅允许Done按钮关闭键盘的XCode实现
移除iOS键盘「隐藏键盘」按钮,仅保留Done按钮关闭的方案
首先明确:iOS系统键盘右下角的「隐藏键盘」按钮(向下箭头样式),无法通过UITextField的公开API直接移除——这是系统键盘的默认控件,苹果没有提供修改或隐藏它的官方接口。
不过可以通过以下两种方案实现「禁止用户用该按钮关闭键盘,仅允许Done按钮操作」的需求:
方案一:监听键盘隐藏事件,强制恢复键盘显示
通过监听键盘即将隐藏的通知,判断是否是用户点击了「隐藏键盘」按钮,若是则让文本框重新成为第一响应者,保持键盘显示。
代码示例(Swift):
class ViewController: UIViewController { @IBOutlet weak var fullnameTextfield: UITextField! override func viewDidLoad() { super.viewDidLoad() // 监听键盘隐藏通知 NotificationCenter.default.addObserver(self, selector: #selector(onKeyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) // 设置文本框代理,处理Done按钮 fullnameTextfield.delegate = self } @objc private func onKeyboardWillHide(notification: NSNotification) { // 如果文本框原本是第一响应者,说明是用户点击了「隐藏键盘」按钮 if fullnameTextfield.isFirstResponder { // 延迟执行,避免键盘闪烁过于明显 DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.fullnameTextfield.becomeFirstResponder() } } } } // 实现UITextFieldDelegate,处理Done按钮逻辑 extension ViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { // 点击Done按钮时关闭键盘 textField.resignFirstResponder() return true } }
这种方式的缺点是键盘会短暂隐藏后立刻弹出,但能达到禁止用户用该按钮关闭键盘的目的。
方案二:自定义键盘(彻底控制)
如果想要完全移除「隐藏键盘」按钮,最彻底的方式是自定义一个键盘,只保留你需要的Done按钮。
实现思路:
- 创建一个自定义UIView,添加Done按钮并设置点击事件
- 将文本框的
inputView设置为这个自定义View - 在Done按钮的点击方法中调用
fullnameTextfield.resignFirstResponder()关闭键盘
代码示例(Swift):
// 自定义键盘View class CustomKeyboardView: UIView { weak var textField: UITextField? override init(frame: CGRect) { super.init(frame: frame) setupKeyboard() } required init?(coder: NSCoder) { super.init(coder: coder) setupKeyboard() } private func setupKeyboard() { self.backgroundColor = .lightGray // 创建Done按钮 let doneButton = UIButton(type: .system) doneButton.setTitle("Done", for: .normal) doneButton.titleLabel?.font = UIFont.systemFont(ofSize: 16) doneButton.addTarget(self, action: #selector(onDoneTapped), for: .touchUpInside) // 添加按钮到键盘View,用AutoLayout布局 doneButton.translatesAutoresizingMaskIntoConstraints = false self.addSubview(doneButton) NSLayoutConstraint.activate([ doneButton.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16), doneButton.centerYAnchor.constraint(equalTo: self.centerYAnchor), doneButton.heightAnchor.constraint(equalToConstant: 44) ]) } @objc private func onDoneTapped() { textField?.resignFirstResponder() } } // 在ViewController中使用自定义键盘 class ViewController: UIViewController { @IBOutlet weak var fullnameTextfield: UITextField! override func viewDidLoad() { super.viewDidLoad() let customKeyboard = CustomKeyboardView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 50)) customKeyboard.textField = fullnameTextfield fullnameTextfield.inputView = customKeyboard } }
这种方案完全由你控制键盘的布局和控件,能彻底避免系统键盘的「隐藏键盘」按钮问题,但需要自己处理键盘的输入逻辑(如果是普通文本输入,还需要添加字母/数字按键等)。
内容的提问来源于stack exchange,提问作者rubberchicken
相关产品推荐
相关产品推荐

