我对斯威夫特相当陌生,我无法理解下面的情况。我试图用几个UIViewController函数扩展UITextFieldDelegate类.
class ViewController: UIViewController{
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self在另一个文件中,如果我用未包装的参数定义函数,则该函数不会被调用.
extension UIViewController: UITextFieldDelegate{
internal func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
print("Text Field Should Begin Editing called")
return true
}但是,如果我打开参数,它就能工作。
internal func textFieldShouldBeginEditing(_ textField: UITextField!) -> Bool 你能帮我理解一下原因吗?谢谢
swift 4.2
发布于 2019-03-10 12:54:00
由于object没有保证对象是非零的,Swift在导入的Objective中使所有参数类型的类和返回类型都是可选的。在使用object对象之前,您应该检查以确保它没有丢失。
如果使用_ textField: UITextField,参数可以为空,因此委托不会调用该方法,因为它在方法签名(即internal func textFieldShouldBeginEditing(_ textField: UITextField!) -> Bool )中寻找非空值。
发布于 2019-03-10 13:57:12
在扩展文件中,您应该扩展ViewController类,而不是UIViewController类。你不需要解开警力。所以应该是这样的:
extension UIViewController: UITextFieldDelegate{
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
print("Should begin editing!")
}
}https://stackoverflow.com/questions/55087780
复制相似问题