我无法让代码识别 HourGoal 和 MinuteGoal 文本字段何时为空。它们永远不会出现为零值或空值,从而导致当我尝试解开这些值时程序崩溃。
import UIKit
class ReadingGoal: UIViewController {
@IBOutlet weak var HourGoal: UITextField!
@IBOutlet weak var MinuteGoal: UITextField!
@IBOutlet weak var NextButton: UIButton!
var mingoal = Int()
var hrgoal = Int()
var secondstoread:Int = 0
var initialtime:Int = Int()
@IBAction func HourEditingDidChange(_ sender: Any) {
NextButton.isEnabled = true
}
@IBAction func MinuteEditingDidChange(_ sender: Any) {
NextButton.isEnabled = true
}
func disable() {
NextButton.isEnabled = false
}
@IBAction func NextButtonIsPressed(_ sender: Any) {
print("GERALDINE IS AWESOME!!!!!")
// ERROR
if HourGoal.text?.isEmpty == false || MinuteGoal.text?.isEmpty == false {
if HourGoal.text != nil && HourGoal.text?.isEmpty == false{
// self.hrgoal = Int(HourGoal.text!)!
print("hr Value exists")
print("\(HourGoal.text!)")
}
else {
NextButton.isEnabled = false
}
if MinuteGoal.text != nil && MinuteGoal.text?.isEmpty == false{
// self.mingoal = Int(MinuteGoal.text!)!
print("min value exists")
print("\(MinuteGoal.text!)")
}
else {
NextButton.isEnabled = false
}
print("in ")
// secondstoread = ((mingoal + (hrgoal*60))*60)
secondstoread = 10
if secondstoread > 0 {
performSegue(withIdentifier: "Mr.Friar-DavisIsAGiantBallOfFloof", sender: self)
}
else {
NextButton.isEnabled = false
}
//function saves text field info to core data
}
}
//for the specific segue 'toBookInfo', certain information is passed through the segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//making sure we are using correct segue
if segue.identifier == "Mr.Friar-DavisIsAGiantBallOfFloof" {
//selecting the destination controller
let detailVC: TimerController = segue.destination as! TimerController
//sending properties to destination view controller
detailVC.seconds = secondstoread
}
else {
// Error sender is not a cell or cell is not in collectionView.
}
}
override func viewDidLoad() {
super.viewDidLoad()
initialtime = secondstoread
}
}
最佳答案
这里不会教你术语,但所有变量都应该像这样以小写开头,甚至是 IBOutlets...
...好吧,我研究了你的代码一段时间:
不惜一切代价避免使用感叹号!!! -> 它经常崩溃的原因是因为你使用了!在任何地方,这种力量都会打开选项并完全破坏 swift 的美丽。
这条线如何与没有选项问题的编译器一起工作?
if HourGoal.text?.isEmpty == false || MinuteGoal.text?.isEmpty == false
您正在以某种方式检查可选值,并且该值肯定为零,因此在代码行之前提供:
guard let hourGoalText = HourGoal.text, let minuteGoal = minuteGoal.text else { //handle code for empty textField
return }
这是检查选项的第一步...现在代码不会崩溃...但老实说没有调试
如果您使用guard let 或 if let 语句,则不会遇到崩溃问题
关于ios - 不将文本字段识别为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44229572/