我想添加textfield的值。我想检查textfield是否为空或检查除int之外的其他值。我是斯威夫特的新手。请帮助任何帮助将得到帮助。
@IBOutlet var label :UILabel!
@IBOutlet var first : UITextField!
@IBOutlet var third : UITextField!
@IBOutlet var second : UITextField!
var bloa :NSString?
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func playPressed(sender: UIButton) {
var a: Int = 0
var b: Int = 0
var c: Int = 0
var d: Int = 0
if first.text!.isEmpty || second.text!.isEmpty || third.text!.isEmpty {
return
}
else
{
// If on first textfield there is another value than int they show
//fatal error: unexpectedly found nil while unwrapping an Optional value
a = (Int)(first.text!)!
b = Int(second.text!)!
c = Int(third.text!)!
d = a + b + c
label?.text = String (format: "%d",d)
}
答案 0 :(得分:2)
试试这个:
if first!.text == "" || second!.text == "" || third!.text == "" {
}
答案 1 :(得分:1)
您不需要以这种方式检查它是否为空:
let alert = UIAlertController(title: "your title", message "move to next VC?", preferredStyle: UIAlertController: UIAlertControllerStyle.Alert)
let action: UIAlertAction = UIAlertAction(title: "yes move to next VC", style: UIAlertActionStyle.Default) {action -> Void in
let rViewController = storyboard.instantiateViewControllerWithIdentifier("rsh") as! R_SVC
self.presentViewController(rViewController, animated: true, completion: nil) })
alert.addAction(defaultAction)
self.presentViewController(alert, animated: true, completion: nil)
您的最终代码将是:
guard let a = Int((first?.text)!), b = Int((second?.text)!) , c = Int((third?.text)!) else {
print("Not convertable to Int or field are empty")
return
}
答案 2 :(得分:0)
答案 3 :(得分:0)
从故事板中将键盘类型设置为数字键盘。然后在代码中执行此操作:
@IBAction func playPressed(sender: UIButton) {
if first?.text?.isEmpty || second?.text?.isEmpty || third?.text?.isEmpty {
}
}