gpt4 book ai didi

ios - 从扩展中获取 ViewController 的实例

转载 作者:行者123 更新时间:2023-11-28 14:25:13 24 4
gpt4 key购买 nike

我想从扩展访问ViewController,然后重写库中的函数,该函数应该更改变量或从特定的 ViewController(在本例中为“ViewController”)调用方法。

我该怎么做?还是有更推荐的选择?

(提示:我不想实例化一个新的 VC)

import PopupDialog

class ViewController: UIViewController {

//e.g. variable and method to access from extension

var score: Int = 0;

func startGame(){
...
}
}
extension PopupDialog{
open override func viewWillDisappear(_ animated: Bool) {
//change variables
//maybe also invoke methods
}
}

最佳答案

您可以使用NotificationProtocol 在ViewController 之间进行通信

通知示例:

创建一个扩展以使用通知名称:

extension Notification.Name {
static let ScoreUpdateNotification = Notification.Name("ScoreUpdateNotification")
}

在First ViewController的DidLoad中添加Observer方法

NotificationCenter.default.addObserver(self, selector: #selector(triggerThisMethod), name: Notification.Name.ScoreUpdateNotification, object: nil)

@objc func triggerThisMethod(_ notification: NSNotification) {
// When the notification arrives, this method will be called
if let object = notification.object {
// If there is Object passed with notification you will get it here.
}
}

发布通知

let objectToPass = 23
NotificationCenter.default.post(name: .ScoreUpdateNotification, object: objectToPass)

协议(protocol)

在 ViewController B 中创建协议(protocol)和弱变量

protocol ProtocolB: class {
func didUpdateScore(_ score: Int)
}

weak var delegate: ProtocolB?

当您从 A 呈现/推送 ViewController B 时

let viewControllerB = // ...
viewControllerB.delegate = self
//present viewControllerB

将协议(protocol)方法添加到 ViewController A

extension ViewController: ProtocolA {
func didUpdateScore(_ score: Int) {
// Do things
}
}

触发方法调用:

delegate?.didUpdateScore(25)

关于ios - 从扩展中获取 ViewController 的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51650475/

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