【发布时间】:2021-07-27 00:08:03
【问题描述】:
所以我有一个带有文本的 UILabel,我必须在 UITextField 中写入以检查 UILabel 和 UITextField 的字符是否相似? 所以我在 C-Lang 和 C-lang 中有一些实践来解决这个问题,我们必须编写整数索引来比较“UITextField”中“UILabel”中的索引。 所以我们有一个字符,如果标签和文本字段中的字符相同,我们只需增加一个索引并必须比较下一个索引(字符)。
我需要比较每个字符。例如,我们有一个字符串“Hello!”。如果我们写“Heklo?”,我们的字符“H”、“e”、“l”、“o”必须是绿色,而我们的“k”和“?”必须是红色的。
我很快尝试做同样的事情,但它不起作用。
import UIKit
class ViewController: UIViewController {
private let textLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "There are a text, which you must text to get the last character of this label!"
label.sizeToFit()
return label
}()
private let resultTextLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.translatesAutoresizingMaskIntoConstraints = false
label.sizeToFit()
return label
}()
private let textField : UITextField = {
let text = UITextField(frame: CGRect(x: 20, y: 300, width: 300, height: 40))
text.placeholder = "Enter text Here!"
text.font = .systemFont(ofSize: 15)
text.autocorrectionType = .no
text.keyboardType = .default
text.returnKeyType = .done
text.clearButtonMode = .whileEditing
text.addTarget(self, action: #selector(checkWrongOrRight), for: .editingChanged)
return text
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(textLabel)
view.addSubview(textField)
view.addSubview(resultTextLabel)
setUpConstraints()
}
@objc func checkWrongOrRight(_ textField: UITextField) {
// ??????????????? I thought that a logic of app could be here
if textLabel.text == resultTextLabel.text {
textLabel.textColor = .green
} else {
textLabel.textColor = .red
}
}
func setUpConstraints() {
textLabel.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20).isActive = true
textLabel.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20).isActive = true
textLabel.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 100).isActive = true
resultTextLabel.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20).isActive = true
resultTextLabel.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20).isActive = true
resultTextLabel.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 500).isActive = true
}
}
那么如何比较 UILabel 和 UITextField 中的字符呢?
【问题讨论】:
-
添加
UITextViewDelegate?
标签: ios swift uikit uitextfield uilabel