调用父ViewController实例方法

时间:2013-01-29 09:11:07

标签: iphone objective-c

我通过以下代码

向视图控制器添加自定义视图
[bTVC addSubview:customView];

现在我想在自定义视图的类中调用父viewController的实例方法

[self.parentViewController instanceMethod];

可能吗?我怎么能这样做?

2 个答案:

答案 0 :(得分:4)

“普通”方法应该是实现指向父视图控件的属性(未保留)委托,但您可能更喜欢使用以下内容:

-(MyCustomUIViewController*)findParentUIViewControllerInSuperViews:(UIView*)myView {
    for (UIView* next = [myView superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[MyCustomUIViewController class]]) {
            return (MyCustomUIViewController*)nextResponder;
        }
    }
    return nil;
}

现在只需致电:

MyCustomUIViewController* myParentViewController = (MyCustomUIViewController*)[self findParentUIViewControllerInSuperViews:self];
[myParentViewController instanceMethod];

无论如何,我还建议你学习委托如何运作,它在很多情况下很有用,你肯定迟早会需要它......

答案 1 :(得分:0)

NSViewController中没有addSubview方法。您可以在NSView中找到它。 如果bTVC是NSView(或其子类)的一个实例,你可以通过向super发送superview来获得你所谓的父视图:[self superview]或self.superview。在你的例子中它将返回bTVC。 NSViewController的工作方式不同,您可以阅读完整的文档here

相关问题