Iphone 调用父ViewController实例方法

Iphone 调用父ViewController实例方法,iphone,objective-c,Iphone,Objective C,我正在通过以下代码向视图控制器添加自定义视图 [bTVC addSubview:customView]; 现在我想在自定义视图的类中调用父viewController的实例方法,如下所示 [self.parentViewController instanceMethod]; 可能吗?如何才能做到这一点?NSViewController中没有addSubview方法。您可以在NSView中找到它。 如果bTVC是NSView的实例(或的子类),则可以通过将superview发送到self:[s

我正在通过以下代码向视图控制器添加自定义视图

[bTVC addSubview:customView];
现在我想在自定义视图的类中调用父viewController的实例方法,如下所示

[self.parentViewController instanceMethod];

可能吗?如何才能做到这一点?

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

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

“正常”方法应该是实现指向父viewController的属性(非保留)委托,但您可能更喜欢使用以下方式:

-(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];
无论如何,我还建议您了解委托是如何工作的,它在许多情况下都很有用,您迟早会需要它……

正常的方法应该是实现一个指向父视图控制器的属性(而不是保留)委托,但您可能更喜欢使用这样的方法:

-(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];

无论如何,我还建议您了解委托是如何工作的,它在许多情况下都很有用,您迟早会需要它…

创建父视图的对象并使用它调用其方法,但这意味着创建一个新对象。。我不能使用添加了自定义视图的ViewController的现有对象吗?创建父视图的对象并使用它调用其方法,但这意味着创建一个新对象。。我不能使用添加了自定义视图的ViewController的现有对象吗?对不起,我使用的是UIViewController和UIViewController对不起,我使用的是UIViewController和UIView