ios - TextField 的代表

标签 ios swift

我遇到了一些事情,但我无法理解。

enter image description here

在我观看的教程中,讲师按下(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
    }

enter image description here

这些方法用于管理和验证来自 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/

相关文章:

ios - 如何在 Xcode 6 (iOS 8) 模拟器上使用 Charles Proxy?

ios - 无法在新开发机器上使用 nil 模型创建 NSPersistentStoreCoordinator

ios - 在 iOS 中使用 Quickblox 的两个不同应用程序可以共享聊天/对话吗?

ios - 我无法从 firebase 数据库获取数据作为子类对象

xcode - 您不能在此版本的 OS X 上使用屏幕保护程序

ios - tableView.setContentOffset 不适用于嵌入在 UIViewcontroller 中的 UITableView

ios - 核心数据建模问题(如何根据关系的关系更新属性?)

ios - Alamofire 读取 header 响应

ios - swift 太聪明?使用 XCTest 测试时检查对象类型

swift - 需要将 UTC 时间转换为设备的当前时区