我遇到了一些事情,但我无法理解。
在我观看的教程中,讲师按下(cntrl + 单击)委托(delegate)选项并将其拖到 ViewController 类中。然后,文本字段选项变得像照片一样。我搜索了很多,找到了解释,但我无法准确理解。
说明:为了能够使用 UITextFieldDelegate 方法,ViewController 类必须采用此协议(protocol)。但是,在使用任何方法之前,我们必须选择此委托(delegate)选项。
我无法理解这个选项。它有什么好处?
最佳答案
因此,为了使用它并理解它,请尝试以下步骤:
1 像这样为您的类采用 UITextFieldDelegate 协议(protocol)
class MyViewController: UIViewController, UITextViewDelegate {
2 为 UITextViewDelegate 实现回调方法。例如:
//MARK: UITextViewDelegate
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
print(textField.text ?? "")
return true
}
这些方法用于管理和验证来自 TextView 的文本。 也许你应该阅读 protocols .
或者,如果您不明白为什么要直接从 Storyboard 中设置委托(delegate),那是因为这样您就不会在类中声明额外的属性。我会无缝完成,你不会在类里面看到这个:
@IBOutlet weak var myTextField: UITextField!
//...
override func viewDidLoad() {
super.viewDidLoad()
myTextField.delegate = self
}
关于ios - TextField 的代表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45756479/