gpt4 book ai didi

ios - 导航堆栈之前 View 之间的协议(protocol)委托(delegate)

转载 作者:行者123 更新时间:2023-12-02 04:42:24 26 4
gpt4 key购买 nike

View1 转至导航 Controller - View2 转至View3

我正在尝试创建从 View3 到 View1 的协议(protocol)委托(delegate)

在 View 1

class NormalUser: UIViewController, NormalUserDelegate {

@objc func showAddressView() {
addressView.isHidden = false
}

override func viewDidLoad() {
super.viewDidLoad()

if let conn = self.storyboard?.instantiateViewController(withIdentifier: "View") as? View
{
conn.delegate = self
}
}
}

在 View 3

weak var delegate: NormalUserDelegate?

func test() {

self.delegate?.showAddressView()

}

协议(protocol)

protocol NormalUserDelegate: class {
func showAddressView()
}

我无法让它发挥作用。有什么想法吗?

最佳答案

在我看来,你有两个不错的选择来使用委托(delegate)模式。 1 个可怕的选项可以工作,但它很老套且懒惰,然后你就有了广播接收器模式。

2个不错的选择

1 - 将委托(delegate)向前传递

class VC1: UIViewController, SomeDelegate {

func delegateFunction() {}

func showNextVC() {
let next = VC2()
next.forwardingDelegate = self
present(next, animated: true)
}
}

class VC2: UIViewController {
var forwardingDelegate: SomeDelegate? = nil

func showNextVC() {
let next = VC3()
next.delegate = forwardingDelegate
present(next, animated: true)
}
}

2 - 将第三个 Controller 传递给第二个 Controller


class VC1: UIViewController, SomeDelegate {

func delegateFunction() {}

func showNextVC() {
let final = VC3()
final.delegate = self

let next = VC2(withControllerToPresent: final)
present(next, animated: true)
}
}

class VC2: UIViewController {
let controller: UIViewController

init(withControllerToPresent controller: UIViewController) {
self.controller = controller
super.init(withNibName: nil, bundle: nil
}

func showNextVC() {
present(controller, animated: true)
}
}

class VC3: UIViewController {
var delegate: SomeDelegate? = nil
}

1 个糟糕的选择

使用单例/全局变量...(请不​​要)

个人意见

我已经完成了前两个选项......它们有效。但广播接收器模式可能更好,因为它更干净。 VC2 不需要将任何内容转发到 3。只需确保您的通知的命名空间足够具体,以免以后被其他任何内容捕获。

关于ios - 导航堆栈之前 View 之间的协议(protocol)委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59964483/

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