View1
segues到导航控制器-View2
segues到View3
我正在尝试创建从View3到View1的协议委托
在View1中
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
}
}
}
在View3中
weak var delegate: NormalUserDelegate?
func test() {
self.delegate?.showAddressView()
}
协议
protocol NormalUserDelegate: class {
func showAddressView()
}
我无法使其工作。任何想法?
最佳答案
我的看法是,您有2个不错的选择来使用委托模式。 1个不错的选择将起作用,但它既笨拙又懒惰,然后您具有广播接收器模式。
2个不错的选择
1-向前传递代表
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-将第三个控制器传递给第二个控制器
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。只需确保对通知的命名空间足够具体,以免以后被其他任何内容捕获。