ios - 从 UIView 到 UIViewController?

标签 ios objective-c cocoa-touch uiview uiviewcontroller

有没有一种内置的方法可以从 UIView 到它的 UIViewController?我知道你可以通过 [self view]UIViewController 到它的 UIView 但我想知道是否有反向引用?

最佳答案

使用 Brock 发布的示例,我对其进行了修改,使其成为 UIView 的类别,而不是 UIViewController,并使其递归,以便任何 subview 都可以(希望)找到父 UIViewController。

@interface UIView (FindUIViewController)
- (UIViewController *) firstAvailableUIViewController;
@end

@implementation UIView (FindUIViewController)
- (UIViewController *) firstAvailableUIViewController {
    UIResponder *responder = [self nextResponder];
    while (responder != nil) {
        if ([responder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)responder;
        }
        responder = [responder nextResponder];
    }
    return nil;
}

@end

要使用此代码,请将其添加到一个新的类文件中(我将其命名为“UIKitCategories”)并删除类数据...将@interface 复制到标题中,并将@implementation 复制到.m 文件中。然后在您的项目中,#import "UIKitCategories.h"并在 UIView 代码中使用:

// from a UIView subclass... returns nil if UIViewController not available
UIViewController * myController = [self firstAvailableUIViewController];

关于ios - 从 UIView 到 UIViewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1340434/

相关文章:

iphone - 允许 View 完全重绘,然后在主线程上执行操作

ios - 将视频和音频 Assets 合并到Swift 3 iOS中后,在视频上添加水印

ios - 如何使用 xib 文件为自定义 UIView 类编写 init 方法

ios - 使用或不使用 shouldRasterize

ios - 将 uitableview 添加到 uiview 后 didselectrowatindexpath not called ios

iOS接收远程通知并打开url

iphone - 核心数据

swift - NSInternalInconsistencyException',原因 : 'Could not load NIB in bundle while fetching 500+ records from the address book database

ios - Storyboard instantiateViewControllerWithIdentifier 返回空 View Controller ?

html - 在 iOS 上将网页精简为文本( Objective-C )