我的应用程序应该像这样工作:
不同的 VC 将他们的选项发送到最后一个。
问题是lastVC中没有出现任何内容(空标签)
出了什么问题?
import UIKit
class MyChoices {
var colour : String?
var style : String?
var size : String?
}
class VC1: UIViewController {
@IBOutlet weak var nextOutlet: UIButton!
@IBOutlet weak var colourLabel: UILabel!
var choice : MyChoices?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
nextOutlet.hidden = true
}
@IBAction func redButton(sender: AnyObject) {
nextOutlet.hidden = false
colourLabel.text = "Red colour selected"
choice?.colour = "Red"
}
@IBAction func blueButton(sender: AnyObject) {
nextOutlet.hidden = false
colourLabel.text = "Blue colour selected"
choice?.colour = "Blue"
}
@IBAction func greenButton(sender: AnyObject) {
nextOutlet.hidden = false
colourLabel.text = "Green colour selected"
choice?.colour = "Green"
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "lastSegue" {
let nextVC = segue.destinationViewController as! lastVC
nextVC.choice = self.choice
}
}
}
VC2和VC3非常接近VC1
class lastVC: UIViewController {
@IBOutlet weak var colourLabel: UILabel!
@IBOutlet weak var styleLabel: UILabel!
@IBOutlet weak var sizeLabel: UILabel!
var choice : MyChoices?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
colourLabel.text = choice?.colour
styleLabel.text = choice?.style
sizeLabel.text = choice?.style
}
最佳答案
问题出在您的对象初始化中。您从未初始化 MyChoice
类来获取各个 VC 内的对象。我刚刚在 Playground 上运行了下面的代码,它的效果就像魅力一样。因此,关键在于,将 var choice : MyChoices?
替换为 var choice : MyChoices? = MyChoices()
:
class MyChoices {
var colour : String?
var style : String?
var size : String?
}
class VC1: UIViewController {
var choice : MyChoices? = MyChoices()
func testMe1() {
self.choice?.colour = "Red"
print("VC1 = \(self.choice?.colour)")
let vc2 = VC2()
vc2.choice = self.choice
vc2.testMe2()
}
}
class VC2: UIViewController {
var choice : MyChoices? = MyChoices()
func testMe2() {
print("VC2 = \(choice?.colour)")
choice?.style = "My Style"
let vc3 = VC3()
vc3.choice = self.choice
vc3.testMe3()
}
}
class VC3: UIViewController {
var choice : MyChoices? = MyChoices()
func testMe3() {
print("VC3 = \(choice?.style)")
choice?.size = "10"
let vc4 = VC4()
vc4.choice = self.choice
vc4.testMe4()
}
}
class VC4: UIViewController {
var choice : MyChoices? = MyChoices()
func testMe4() {
print("VC4 = \(choice?.size)")
}
}
// Forceful run to check object properties
let vc1 = VC1()
vc1.testMe1()
关于ios - 在 Swift 中将数据从第一个 VC 发送到第四个 VC 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32946187/