我有 2 个 View Controller ,在 vC1 中声明了一个变量 isShowListAsked : Bool = false
,单击 map 按钮后,它会转到 vC2 。在vC2中有一个名为List的按钮。
我要那个 :
单击列表按钮后,它返回到 vC1,并且 vC1 变量值应更改为 true。但它仍然是 False。
请帮助我。
提前致谢。
点击列表按钮后,我可以返回到 vC1,但无法设置isShowListAsked = true .我尝试获取{}设置{}。
在 vC1 中:
class vC1 : UIViewController
{
var isShowListAsked : Bool = false
var IsShowListAsked : Bool {
get {
return isShowListAsked
}
set{
isShowListAsked = newValue
}
}
}
然后点击“In vC2”后:
class vC2 : UIViewController
{
var vc = vC1()
@IBAction func mapListSegmentTapped(_ sender: Any) {
if mapListSegment.selectedSegmentIndex == 1
{
vc.IsShowListAsked = true
}
if mapListSegment.selectedSegmentIndex == 0
{
vc.IsShowListAsked = false
}
}
}
返回后我正在检查 viewWillappear() 中的变量值
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print(" isshowListAsked = \(IsShowListAsked) ") // print false
}
预期结果:
print(" isshowListAsked = \(IsShowListAsked) ") // print True
实际结果:
print(" isshowListAsked = \(IsShowListAsked) ") // print false
最佳答案
使用闭包
来解决您的问题陈述。
在VC2
中创建一个((Bool)->())?
类型的闭包
,并使用相关的调用它
值,即mapListSegmentTapped(_:)
方法中的 true/false
class VC2: UIViewController {
var handler: ((Bool)->())?
@IBAction func mapListSegmentTapped(_ sender: Any) {
if mapListSegment.selectedSegmentIndex == 1 {
self.handler?(true)
} else if mapListSegment.selectedSegmentIndex == 0 {
self.handler?(false)
}
}
}
现在,当您呈现
来自VC1的
即VC2
的实例
时,设置此闭包
class VC1 : UIViewController {
var isShowListAsked: Bool = false
func onTapMapButton(_ sender: UIButton) {
if let controller = self.storyboard?.instantiateViewController(withIdentifier: "VC2") as? VC2 {
controller.handler = {[weak self] (value) in
self?.isShowListAsked = value
print(self?.isShowListAsked)
}
self.present(controller, animated: true, completion: nil)
}
}
}
关于swift - 如何更改另一个类中声明的类的变量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56472064/