我正在学习swift3编程,但在执行我的计算器应用程序后,它之间崩溃了。请检查以下代码。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var aLabel: UILabel!
@IBOutlet weak var commmon_button: UIButton!
var a: Int?
var b: Int?
var sum: Int?
var val = ""
@IBOutlet weak var text_feild: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func clik_button(_ sender: UIButton) {
val=String(sender.tag)
text_feild.text = text_feild.text! + val
}
@IBAction func fn_addition(_ sender: UIButton) {
a = Int(text_feild.text!)
}
@IBAction func fn_answer(_ sender: UIButton) {
b = Int(text_feild.text!)
sum = a! + b!
a = 0
b = 0
text_feild.text = nil
text_feild.text = String(sum!)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
在运行期间,我通过说线程1断点2.1
在fn_addition上崩溃答案 0 :(得分:0)
将您的变量初始化为
var a = 0
var b = 0
var sum = 0
用以下方法替换您的方法。
@IBAction func clik_button(_ sender: UIButton) {
guard let value = String(sender.tag), let text = text_feild.text
else {
return
}
text_feild.text = text + value
}
@IBAction func fn_addition(_ sender: UIButton) {
guard let aValue = Int(text_feild.text)
else{
return
}
a = aValue
}
@IBAction func fn_answer(_ sender: UIButton) {
guard let bValue = Int(text_feild.text)
else{return}
b = bValue
sum = a + b
a = 0
b = 0
text_feild.text = ""
text_feild.text = String(sum)
}
建议: 您正在使用相同的文本字段来获取a,b值以及显示和结果。最好使用两个不同的文本字段分别获取a和b值。拿一个标签来显示总和值。