如何检查用户给出的输入UITextfield
的字符串是否是字符串数组的一部分?如果它是数组的一部分,如何在UITextfield
中显示它的值?
例如,一个用户的put是" "在UITextField
。它应该是字母字符串数组的一部分,如果不显示错误。如果是字符串数组的一部分,则在另一个UITextfield
var alphabet: [String] = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
var alphaDictionary = [String: Int]()
for val in 1...alphabet.count {
var i: Int = 1
for a in alphabet {
alphaDictionary[a] = i
i += 1
}
}
你可以让你的视图控制器实现UITextFieldDelegate
委托方法textField:shouldChangeCharactersInRange:replacementString:
,它将接收输入。这个委托将验证输入,并显示带有错误的警报,或者用您映射的值更新secondTextField
:
extension YourViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let validInput = alphabet.contains(string)
if validInput {
let score = textField.text!.reduce(0) { $0 + alphaDictionary[String($1)]! }
resultView.text = textField.text! + String(score)
}
else {
let alert = UIAlertController(title: "Invalid character", message: "The character you entered is not part of the alphabet", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .default)
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
return validInput
}
}
确保你将视图控制器设置为UITextField
的委托:
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
}
@IBAction func goTapped(_ sender: UIButton) {
let inputLetter = (userAlphabet.text!)
let inputWord = (userWord.text!)
let word = inputWord.map({String($0)})
if alphabet.contains(inputLetter) {
// it exists, do something
for val in 1...alphabet.count {
var i: Int = 1
for a in alphabet {
alphaDictionary[a] = i
i += 1
}
}
let alpha = inputLetter
resultView.text = String(alphaDictionary[alpha]!)
Here it displays both alphabet and its value in textview
for ele in word{
print(alphaDictionary[ele]!)
score += alphaDictionary[ele]!
}
resultView.text = inputWord
resultView.text = String(score)
在这里显示word的得分,但不是两者都显示。如何将另一组数据附加到textView