如何同时更改文本字段和标签中的文本 [英] How to change text in text field and label at the same time
问题描述
有人知道如何同时在 textField 和 label 上写消息吗?当我在 textField 写消息时,我想在标签上看到那个文本,一个字符一个字符,同时......
Anybody have idea how to write message at the textField and label at the same time? When I write message at the textField, I would like to see that text at the label, char by char, simultaneously....
是否有任何 UItextField 委托?
Is there any UItextField delegate for that?
推荐答案
我们可以将 SH_Kahn 展示的方法更进一步:
We can bring the approach SH_Kahn has shown a bit further:
import UIKit
extension UILabel {
@objc
func input(textField: UITextField) {
self.text = textField.text
}
}
我们添加了一个签名与添加目标机制兼容的方法.此方法只会获取 textField 的文本并将其设置为标签的文本.
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.
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)
}
}
这篇关于如何同时更改文本字段和标签中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!