如何从 points
的IBAction方法访问 ViewController
属性并将其传递给 scoreLabel
SecondViewController
?
import UIKit
class ViewController: UIViewController {
var points: Int = 0
@IBAction func action(sender: UIButton) {
points += 1
}
}
class SecondViewController: UIViewController {
@IBOutlet weak var scoreLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
}
答案 0 :(得分:1)
注意:这假设您从SecondViewController
开始ViewController
。
在SecondViewController
中,声明一个名为score
的变量或类似的变量:
var score: Int = 0
在ViewController
中,按照以下方式实施prepareForSegue
方法:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "YourSegueIdentifierForSecondViewController" {
if let secondViewController = segue.destination as? SecondViewController {
secondViewController.score = points
}
}
}
然后在SecondViewController
的{{1}}中,您可以为自己的标签设置分数:
viewDidLoad