【问题标题】:Swift method doesn't override any method from its superclassSwift 方法不会覆盖其超类中的任何方法
【发布时间】:2016-08-11 08:19:32
【问题描述】:

我对 Swift 比较陌生,我正在学习一些基本教程,但我似乎遇到了一些方法的问题,这些方法试图让用户按回车键以最小化键盘或单击键盘,然后键盘会消失,我明白为什么我会收到这些错误,但不知道如何修复它,我觉得我正在使用的新版本 Swift 中可能发生了一些变化,因为他使用的版本比我旧,任何人都可能请解释如何解决这两个错误?任何帮助将不胜感激这里是我的源代码:(第一个错误,类型“viewController”的值没有成员“文本”,其次,touchesBegan 方法不会覆盖其超类中的任何方法)

import UIKit

class ViewController: UIViewController {

@IBAction func buttonPressed(sender: AnyObject) {

   label.text = textArea.text

}

@IBOutlet weak var textArea: UITextField!

@IBOutlet weak var label: UILabel!

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

    self.text.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 textFieldShouldReturn(textField: UITextField!) -> Bool {

    textField.resignFirstResponder()

    return true

}

}

【问题讨论】:

  • 不要将代码发布为图片,请确保创建MVCE
  • 您必须在视图控制器上实现 UITextfieldDelegate 才能做到这一点。

标签: iphone swift swift2


【解决方案1】:

根据您发布的图片,您在这里有 2 个问题:

1) 你正在使用的方法 touhesBegan is not correct:

正确的一个:

func touchesBegan(_ touches: Set<UITouch>, withEvent event: UIEvent?)

你的:

func touchesBegan(touches: NSSet, withEvent event: UIEvent)

我想你想要一个 UITextField 的委托,所以这个不是 corerct:touchesBegan 是 UIReponder 委托的方法,而不是 UITextFieldDelegate 的方法。

Here你可以找到 UITextFieldDelegate 的参考。

2) 变量text 不存在于您的代码中。我想你想改用textArea

希望对你有所帮助,编码愉快!

【讨论】:

  • 谢谢!是的,我确实使用了错误的功能,非常感谢我的朋友 :) 两个问题都已修复。
【解决方案2】:

在您的情况下更改以下内容:

而不是:

self.text.delegate = self

改变:

self.textArea.delegate = self


override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    }

对于委托添加这样的

class ViewController: UIViewController, UITextFieldDelegate {
}

【讨论】:

  • 哦,我知道这会很简单,感谢第一个错误已解决。我已经删除了 override 关键字,但它显示“方法 touchesBegan 与 Objective-C 选择器 touchesBegan:withEvent 与超类中的方法 touchesBegan 冲突”,这听起来像是需要覆盖其他方法
  • @DavidThomlinson 检查并修改:
  • 您需要在 touchesBegan 中更改方法参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-08
相关资源
最近更新 更多