从外部访问视图/视图控制器?

时间:2019-08-31 00:24:54

标签: ios swift uiview uiviewcontroller

在我的应用中,我有一个自定义视图CustomViewA,其中包含并委托了另一个视图CustomViewB
最后,应该在包含的View Controller CustomViewB上接收MyViewController的结果。

最近,我遇到了这种方便的方法来访问父视图控制器的一个视图,就像这样:

extension UIResponder {
    var parentViewController: UIViewController? {
        return next as? UIViewController ?? next?.parentViewController
    }
}

因此,这看起来像是很奇怪的练习,但是编写类似这样的内容会有负面影响:

// CustomViewA.swift
func protocolActionFromCustomViewB(objectToPass: CustomObject) {
    if let parent = self.parentViewController as? MyViewController {
        parent.performAction(with: objectToPass)
    }
}

是否在创建另一个特定协议或发送通知?

同一点,从视图的超级视图访问值或调用函数是否有负面影响?像这样:

if let superview = superview as? MyCustomView {
    let object = superview.someObject
    superview.someFunction()
    ...
}

谢谢。

0 个答案:

没有答案
相关问题