我想知道检查/验证我的影响文本字段的最简单最简单的方法是什么,它只能从1-80输入?我的编码仍然非常生疏,我尝试做了" if(Int(impact.text!)!= 1 ... 80)"但它没有用。
的ViewController
import UIKit
import FirebaseDatabase
class TryingOut2Controller: UIViewController {
@IBOutlet var titleLabel: UILabel!
@IBOutlet var impact: UITextField!
@IBOutlet var rigour: UITextField!
@IBOutlet var response: UITextField!
@IBOutlet var total: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.text = postData[myIndex]
impact.addTarget(self, action: #selector(textChanged), for: .editingChanged)
rigour.addTarget(self, action: #selector(textChanged), for: .editingChanged)
response.addTarget(self, action: #selector(textChanged), for: .editingChanged)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func textChanged() {
let impactValue = Int(impact.text!)
let rigourValue = Int(rigour.text!)
let responseValue = Int(response.text!)
total.text = String(describing:
(impactValue ?? 0) + (rigourValue ?? 0) + (responseValue ?? 0)
)
}
@IBAction func button1(_ sender: Any) {
if (Int(impact.text!) != 1...80)
{
//create alert
}
else {
}
答案 0 :(得分:1)
最好的方法是实现委托函数textField(_:shouldChangeCharactersIn:replacementString:)
(参见https://developer.apple.com/documentation/uikit/uitextfielddelegate/1619599-textfield)
您可以实现此操作以检查当前值加上新输入是否可以转换为Int,并且包含1 ... 80。
答案 1 :(得分:1)
最好的方法是添加一个动作方法"编辑已更改"到你的textField: 并检查您的文本字段是否具有大于80的值
@IBAction func valueChange(_ sender: Any) {
if let number = Int(self.impact.text!){
if number > 80 || number < 0 {
let alert = UIAlertController(title: "Error", message: "Enter a Valid Number", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(alertAction)
self.present(alert, animated: true, completion: nil)
}
}
}
答案 2 :(得分:1)
字符串甚至可以直接与字母表中的字母或数字进行比较。您可以将范围比较为:例如
let value = "90"
if value > "1" && value < "80" {
print("in range 1-80")
} else {
print("out of range 1-80")
//create alert in your case
}
//prints out of range 1-80
希望有所帮助...... !!!
答案 3 :(得分:0)
func textField(textField: UITextField,
shouldChangeCharactersInRange range: NSRange,
replacementString string: String) -> Bool
{
var startString = ""
if (self.impact.text! = nil)
{
startString += self.impact.text!
}
startString += string
var limitNumber = startString.toInt()
if limitNumber > 80 || limitNumber < 0
{
return false
}
else
{
return true;
}
}