gpt4 book ai didi

swift - 无法关闭键盘,UITextField 委托(delegate)被调用 OK

转载 作者:搜寻专家 更新时间:2023-11-01 05:42:21 24 4
gpt4 key购买 nike

这个问题一直让我抓狂。似乎无论我尝试什么,一旦键盘显示在我的简单 Swift 程序中,我都无法隐藏它。

当我在 textFieldShouldReturn 中 resignFirstResponder() 时它不起作用,当通过从 touchesBegan(...) 调用 endEditing() 处理背景触摸时它也不起作用。当我为它们设置调试器断点时,我可以看到这些各自的方法都被调用,因此委托(delegate)已正确设置并按预期被调用。

以下是我采取的具体步骤:

  • 创建一个新的单 View 应用程序 Swift 项目
  • 将 UITextField 拖到 View 上,连接 IBOutlet,并将 ViewController 设置为 UITextFieldDelegate。
  • 在 iPhone 6 模拟器或 iPhone 6 设备上运行
  • 一旦键盘出现,它就永远不会消失!!

我没有想法 - 我错过了什么???

这是我的 ViewController 的全部内容:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var myTextField: UITextField!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

myTextField.delegate = self
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true)
}

func textFieldDidBeginEditing(textField: UITextField!) {
return
}

func textFieldShouldEndEditing(textField: UITextField!) -> Bool {
return false
}

func textFieldShouldReturn(textField: UITextField!) -> Bool {
textField.resignFirstResponder()
return true
}
}

最佳答案

您正在从 'textFieldShouldEndEditing' 返回 'false'。以下是 'UITextFieldDelegate' 文档的摘录:

Return Value

YES if editing should stop; otherwise, NO if the editing session should continue

Discussion

This method is called when the text field is asked to resign the first responder status. This might occur when your application asks the text field to resign focus or when the user tries to change the editing focus to another control. Before the focus actually changes, however, the text field calls this method to give your delegate a chance to decide whether it should.

Normally, you would return YES from this method to allow the text field to resign the first responder status. You might return NO, however, in cases where your delegate detects invalid contents in the text field. By returning NO, you could prevent the user from switching to another control until the text field contained a valid value.

Source

因此,要么从中返回 'true' 要么完全删除该方法,除非您真的需要在其中做一些有用的事情。 'textFieldDidBeginEditing''touchesBegan' 也应该被删除。我真的很惊讶相同的代码在 Objective-C 中工作。

关于swift - 无法关闭键盘,UITextField 委托(delegate)被调用 OK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27092268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com