我有一个带有6个按钮的视图控制器,它们全部转移到具有表视图的另一个视图控制器。根据按下的按钮,使用表视图将不同的值传递给视图控制器:
@IBAction func englishButton(_ sender: Any) {
valueToPass = "English"
}
@IBAction func scienceButton(_ sender: Any) {
valueToPass = "Science"
}
@IBAction func historyButton(_ sender: Any) {
valueToPass = "History"
}
@IBAction func foriegnLanguageButton(_ sender: Any) {
valueToPass = "Foriegn Language"
}
@IBAction func mathButton(_ sender: Any) {
valueToPass = "Math"
}
@IBAction func otherSubjectsButton(_ sender: Any) {
valueToPass = "Other Subjects"
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?){
if (segue.identifier == "english") {
// initialize new view controller and cast it as your view controller
let viewController = segue.destination as! BuyMenuController
// your new view controller should have property that will store passed value
viewController.passedValue = valueToPass
}
if (segue.identifier == "science") {
// initialize new view controller and cast it as your view controller
let viewController = segue.destination as! BuyMenuController
// your new view controller should have property that will store passed value
viewController.passedValue = valueToPass
}
if (segue.identifier == "history") {
// initialize new view controller and cast it as your view controller
let viewController = segue.destination as! BuyMenuController
// your new view controller should have property that will store passed value
viewController.passedValue = valueToPass
}
if (segue.identifier == "foriegnLanguage") {
// initialize new view controller and cast it as your view controller
let viewController = segue.destination as! BuyMenuController
// your new view controller should have property that will store passed value
viewController.passedValue = valueToPass
}
if (segue.identifier == "math") {
// initialize new view controller and cast it as your view controller
let viewController = segue.destination as! BuyMenuController
// your new view controller should have property that will store passed value
viewController.passedValue = valueToPass
}
if (segue.identifier == "otherSubjects") {
// initialize new view controller and cast it as your view controller
let viewController = segue.destination as! BuyMenuController
// your new view controller should have property that will store passed value
viewController.passedValue = valueToPass
}
}
这里的问题是每当我按下scienceButton时,传递给下一个视图控制器的值都是nil或者在它之前传递的值。再次点击时,传递的值是"科学"喜欢它的假设。这只发生在那个按钮上,任何想法为什么会发生这种情况? (我已尝试使用if-else if结构设置它。)
答案 0 :(得分:1)
您不应将@IBAction
方法与直接链接到Interface Builder中的操作的segue结合使用,因为可以在执行函数之前执行segue。
您应该将segue链接到视图控制器对象,并在设置变量后以@IBAction
函数以编程方式执行它。