访问@IBAction 的 属性 of ViewController 并将其传递给 SecondViewController
Accessing @IBAction's property of ViewController and pass it to SecondViewController
如何从 ViewController
的 IBAction 方法访问 points
属性 并传递它至 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()
}
}
注意:这是假设您要从 ViewController
.
转到 SecondViewController
在 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
的viewDidLoad
中,你可以为你的标签设置分数:
scoreLabel.text = String(score)
如何从 ViewController
的 IBAction 方法访问 points
属性 并传递它至 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()
}
}
注意:这是假设您要从 ViewController
.
SecondViewController
在 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
的viewDidLoad
中,你可以为你的标签设置分数:
scoreLabel.text = String(score)