![](/img/trans.png)
[英]How to change a label text color when pressed on a table view with swift?
[英]How to change label color when you change label text
我是新來的...我有一個文本字段和一個標簽...如果文本字段中的消息和標簽文本不相等,我想更改標簽顏色。 這是我的開始:
@IBAction func tapMeButton(_ sender: Any) {
label.text = txtField.text
}
我怎樣才能做到這一點?
將此行添加到viewDidLoad
textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
和
@objc func textFieldDidChange(_ textField: UITextField) {
if(label.text != txtField.text)
{
label.textColor = UIColor.red
}
}
@IBAction func tapMeButton(_ sender: Any) {
label.text = txtField.text
}
UITextField提供委托方法,您可以使用此代碼檢查兩個Value是否相同。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let nsString = textField.text as NSString?
let newString = nsString?.replacingCharacters(in: range, with: string)
if(self.lbl.text != newString) {
self.lbl.textColor = UIColor.red
}
else {
self.lbl.textColor = UIColor.green
}
return true;
}
首先添加目標以獲取文本更改。
textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
func textFieldDidChange(_ textField: UITextField) {
if(label.text != textField.text)
{
label.textColor = UIColor.red
}
}
您還可以看到以下內容: https : //stackoverflow.com/a/28395000/5167909
為此,您必須更多地了解文本字段,
每個文本字段都帶有委托方法來圍繞它執行各種功能。 所以首先在您的viewDidLoad方法中,像這樣添加委托
yourTextField.delegate = self
通過添加文本擴展名將textFieldDelegate分配給您的類,從而添加委托方法。 它將在用戶開始輸入時以及甚至添加到textField之前實時為您提供文本
extension YourViewController:UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if let text = textField.text as NSString? { let txtAfterUpdate = text.replacingCharacters(in: range, with: string) if txtAfterUpdate == label.text { label.backgroundColor = UIColor.red } else { label.backgroundColor = UIColor.black } } return true } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.