简体   繁体   English

如何在文本字段和标签中同时更改文本

[英]How to change text in text field and label at the same time

Anybody have idea how to write message at the textField and label at the same time? 有人知道如何在textField和标签上同时写消息吗? When I write message at the textField, I would like to see that text at the label, char by char, simultaneously.... 当我在textField上写消息时,我希望同时在标签上逐个字符地看到该文本。

Is there any UItextField delegate for that? 是否有任何UItextField委托?

Try adding a listener to editingChanged of the textfeild 尝试添加一个监听到textfeild的editingChanged

textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

and

@objc func textFieldDidChange(_ textField: UITextField) {

 yourLabel.text = textField.text

}

We can bring the approach SH_Kahn has shown a bit further: 我们可以将SH_Kahn展示的方法进一步介绍一下:

import UIKit


extension UILabel {
    @objc
    func input(textField: UITextField) {
        self.text = textField.text
    }
}

We add a method with a signature compatible with the add target mechanism. 我们添加一个签名与添加目标机制兼容的方法。 This method just will get textField's text and set it to the label's text. 该方法只是获取textField的文本并将其设置为标签的文本。

class ViewController: UIViewController {

    @IBOutlet weak var outputLabel: UILabel!
    @IBOutlet weak var inputField: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.inputField.addTarget(outputLabel, action: #selector(UILabel.input(textField:)), for: .editingChanged)
    }


}

But if we need it more often, we might would like to make it even easier to use: 但是,如果我们更经常需要它,我们可能希望使其更易于使用:

extension UILabel {
    @objc
    func input(textField: UITextField) {
        self.text = textField.text
    }

    func connect(with textField:UITextField){
        textField.addTarget(self, action: #selector(UILabel.input(textField:)), for: .editingChanged)
    }
}


class ViewController: UIViewController {

    @IBOutlet weak var outputLabel: UILabel!
    @IBOutlet weak var inputField: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        outputLabel.connect(with: inputField)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM