Xcode 9 Swift 4:如何在数字键盘自定义Done按钮中调用textFieldShouldReturn
嘿,我之前也碰到过数字键盘没有Done键的坑,刚好能给你支招~针对你想在自定义Done按钮里调用textFieldShouldReturn的需求,有两个实用方案:
方案一:直接调用
textFieldShouldReturn方法 既然你已经通过代码添加了Done按钮,只需要在按钮的点击事件里直接传入对应的文本框调用这个Delegate方法就行。注意这个方法返回一个Bool值,你可以根据需要处理返回结果,或者直接忽略:
@IBAction func doneButtonPressed(_ sender: UIButton) { // 替换成你实际的文本框实例 let shouldReturn = textFieldShouldReturn(yourNumberTextField) // 如果需要的话,根据shouldReturn的值做后续处理 yourNumberTextField.resignFirstResponder() // 记得收起键盘 }
方案二:抽离核心逻辑到独立函数(更推荐)
直接调用Delegate方法虽然快捷,但从代码结构来说,把业务逻辑(发送本地通知)和键盘回调耦合在一起不是最优解。更好的做法是把textFieldShouldReturn里的通知发送逻辑抽成单独的函数,这样不管是键盘的Return键还是自定义Done按钮,都调用这个函数:
// 把发送通知的核心逻辑单独封装 private func sendLocalNotification() { guard let inputNumber = yourNumberTextField.text, !inputNumber.isEmpty, let number = Int(inputNumber) else { // 处理输入为空或非数字的情况,比如提示用户 return } // 这里写你原本在textFieldShouldReturn里的通知创建代码 // 示例:创建通知内容 let content = UNMutableNotificationContent() content.title = "本地通知" content.body = "你输入的数字是:\(number)" content.sound = UNNotificationSound.default // 设置触发条件(比如立即触发) let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false) let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) // 添加通知请求 UNUserNotificationCenter.current().add(request) { error in if let error = error { print("通知添加失败:\(error.localizedDescription)") } } } // 原来的textFieldShouldReturn方法 func textFieldShouldReturn(_ textField: UITextField) -> Bool { sendLocalNotification() textField.resignFirstResponder() return true } // Done按钮的点击事件 @IBAction func doneButtonPressed(_ sender: UIButton) { sendLocalNotification() yourNumberTextField.resignFirstResponder() }
这个方案的好处是代码复用性更高,后续如果要修改通知逻辑,只需要改sendLocalNotification一个地方就行,也更容易调试和维护。
最后提醒一下,确保你的Done按钮已经正确关联到点击事件,文本框的Delegate也已经设置好哦~
内容的提问来源于stack exchange,提问作者Gina
相关产品推荐
相关产品推荐

