我有一个非常复杂的函数在一个视图控制器中生成一个值(让我们称之为<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Divs</title>
</head>
<body>
<section>
<div class="holder">
<div class="other-div fixed">This div should stay fixed for a while</div>
<div class="sticky">This div will become fixed on scroll</div>
</div>
</section>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
)。此值在firstVC
中使用,但我还希望稍后在其他视图控制器中使用此值(我们将其称为firstVC
)。我知道我可以设置一个协议来重新运行该函数,但这只需要额外的时间,我宁愿只传递该值。 thirdVC
和firstVC
之间不存在segue,thirdVC
将被打开并使用该值的时间未知,将在稍后的某个时间。 (我仍然可以通过以下方式访问thirdVC
:thirdVC
- &gt; firstVC
- &gt; secondVC
)。我想可以设置如下:
thirdVC
//In firstVC
var currentVal: String = "Hello"
@IBAction func button(_ sender: UIButton){
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let thirdVC: thirdVC = storyBoard.instantiateViewController(withIdentifier: "thirdVC")
thirdVC.passedValue = currentVal
}
是passedValue
中的变量。但是,这并未传递任何信息,因为当我尝试检查thirdVC
passedValue
thirdVC
上的viewDidLoad()
时它是空的...我也尝试稍后通过检查值按钮(确保在传递信息之前viewDidLoad()
运行不是问题)并且它仍然是空的。
答案 0 :(得分:1)
您需要在设置vc时设置该值,可以使用didSet完成,如下所示。
var currentVal: String = "Hello"
@IBAction func button(_ sender: UIButton){
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let thirdVC: thirdVC = storyBoard.instantiateViewController(withIdentifier: "thirdVC")
storyBoard.instantiateViewController(withIdentifier: "thirdVC")
thirdVC.passedValue = currentVal
self.present(thirdVC, animated: true, completion: nil)
}
第三个vc ..
class thirdVc: UIViewController {
var someValue: String? = nil
// MARK: - Value to set when passed
var passedValue: String! {
didSet {
self.someValue = passedValue
}
}
override func viewDidLoad() {
super.viewDidLoad()
print(self.someValue) // "Hello"
}
}