gpt4 book ai didi

ios - Swift:不知道如何调用我的委托(delegate)

转载 作者:行者123 更新时间:2023-11-28 09:09:52 26 4
gpt4 key购买 nike

我是 Swift 的新手。我完全无法理解委托(delegate)。我有两个 View Controller ,我需要为另一个我想使用委托(delegate)的 Controller 设置 var。我在这里搜索了很多主题,但没有任何帮助。我的 View Controller B 有一个 var myFlag,我想从 View Controller A 设置它。这里是 View Controller B 代码

protocol flagDelegate {       
func anyFlag(flag: Bool!)
}

class myBViewController: UIViewController {
var myFlag: Bool = false

override func viewDidLoad() {
super.viewDidLoad()
println("myFlag: \(self.myFlag)")
}

override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
println("myFlag: \(self.myFlag)")
}

func anyFlag(flag: Bool!) {
self.myFlag = flag
}
}

View Controller A 有一个按钮,它用代码加载 View Controller B:

@IBAction func addButton(sender: UIBarButtonItem) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("myNC") as! UIViewController
self.presentViewController(vc, animated: true, completion: nil)
}

myNC 是一个包含 View Controller B 的导航 Controller 。我不知道如何设置委托(delegate)和调用它。请问你能帮帮我吗!提前致谢!

最佳答案

如果 View Controller A 在它即将显示的 View Controller ( View Controller B)上设置属性,则不需要使用委托(delegate)模式。委托(delegate)模式用于向后通信(从 B 到 A)。

所以你可以像这样在呈现 View Controller 之前设置一个属性:

@IBAction func addButton(sender: UIBarButtonItem) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let navigationVC = storyboard.instantiateViewControllerWithIdentifier("myNC") as! UINavigationController

// get a reference to your VC
let rootViewController = navigationVC.viewControllers[0] as MyBViewController

// set the property
rootViewController.myFlag = true // or false

// or you could call the method you wrote
rootViewController.anyFlag(true)

// present the view controller
self.presentViewController(navigationVC, animated: true, completion: nil)
}

关于ios - Swift:不知道如何调用我的委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29567094/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com