当我在选择器视图中选择目标2都工作正常时,下一个视图控制器上的标签文本将更新,一切正常。但是,如果我选择Target 1-打开下一个ViewController时没有任何错误,但标签文本为空nil。
如果您能帮助我或以其他方式进行评估,我将不胜感激。我只是在使用if else语句来检查textField。
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let resultsVC = segue.destination as! ResultsViewController
var declinationDegr = Int()
if (bodyTextField.text?.contains("Target 1"))! {
declinationDegr = declinationDegreeTarget1
} else if (bodyTextField.text?.contains("Target 2"))! {
declinationDegr = declinationDegreeTarget2
}
var declinationMinutes = Double()
if (bodyTextField.text?.contains("Target 1"))! {
declinationMinutes = declinationMinutesTarget1
} else if (bodyTextField.text?.contains("Target 2"))! {
declinationMinutes = declinationMinutesTarget2
}
var declinationDir = String()
if (bodyTextField.text?.contains("Target 1"))! {
declinationDir = declinationDirTarget1
} else if (bodyTextField.text?.contains("Target 2"))! {
declinationDir = declinationDirTarget2
resultsVC.bdeclString = "\(declinationDegr)º\(String(format: "%.1f", declinationMinutes))'\(declinationDir)"
}
答案 0 :(得分:0)
首先,我认为您缺少最后一个if / else语句的右花括号。
var declinationDir = String()
if (bodyTextField.text?.contains("Target 1"))! {
declinationDir = declinationDirTarget1
} else if (bodyTextField.text?.contains("Target 2"))! {
declinationDir = declinationDirTarget2
} // CLOSING BRACE MISSING
resultsVC.bdeclString = "\(declinationDegr)º\(String(format: "%.1f", declinationMinutes))'\(declinationDir)"
第二,我将重新组织代码,以避免不必要的字符串比较和强制展开:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let resultsVC = segue.destination as? ResultsViewController else {
// error handling and
return
}
guard let targetText = bodyTextField.text else {
// error handling and
return
}
var declinationDegr = Int()
var declinationMinutes = Double()
var declinationDir = String()
if (targetText.contains("Target 1")) {
declinationDegr = declinationDegreeTarget1
declinationMinutes = declinationMinutesTarget1
declinationDir = declinationDirTarget1
} else if (targetText.contains("Target 2")) {
declinationDegr = declinationDegreeTarget2
declinationMinutes = declinationMinutesTarget2
declinationDir = declinationDirTarget2
} else {
// error handling
}
resultsVC.bdeclString = "\(declinationDegr)º\(String(format: "%.1f", declinationMinutes))'\(declinationDir)"
}