【问题标题】:How to get UIViewController of a UIView's superview in iOS?如何在 iOS 中获取 UIView 的超级视图的 UIViewController?
【发布时间】:2011-01-19 13:20:10
【问题描述】:

我有一个 UIViewController,其中我从界面生成器添加了一个 UITextView。现在我想在单击超链接或电话号码时推送视图。我能够使用我在 stackoverflow 中找到的方法检测单击了哪个 url。这是方法

@interface UITextView (Override)
@end

@class WebView, WebFrame;
@protocol WebPolicyDecisionListener;

@implementation UITextView (Override)

- (void)webView:(WebView *)webView decidePolicyForNavigationAction:(NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id < WebPolicyDecisionListener >)listener
{
    NSLog(@"request: %@", request);
}
@end

现在我想获取 textview 的 superview 的 viewController,这样当我点击 URL/电话号码时,我可以推送另一个 viewController。

【问题讨论】:

    标签: ios objective-c uiview uiviewcontroller iphone-sdk-3.0


    【解决方案1】:

    你不能直接访问它,但是你可以通过遍历响应者链找到下一个视图控制器(如果有的话)。

    the Three20 framework 就是这样做的:

    - (UIViewController*)viewController
    {
        for (UIView* next = [self superview]; next; next = next.superview)
        {
            UIResponder* nextResponder = [next nextResponder];
    
            if ([nextResponder isKindOfClass:[UIViewController class]])
            {
                return (UIViewController*)nextResponder;
            }
        }
    
        return nil;
    }
    

    【讨论】:

    • 哇,谢谢。使用three20,不知道。我总是创建一个代表。对于任何有兴趣在three20中使用它的人。只需导入#import "Three20UICommon/UIView+TTUICommon.h"
    • 请注意,three20 框架似乎不再维护。尽管该解决方案似乎仍然有效。
    【解决方案2】:

    请注意,-webView:decidePolicyForNavigationAction:... 是一种未记录的方法(无论如何都适用于 iPhoneOS。它已记录在 Mac OS X 中),如果适用于 AppStore,该应用程序可能会被拒绝。


    视图控制器不与视图关联。只有反向适用。要访问视图控制器,请将其设为全局可访问的变量或属性。

    如果使用界面构建器,通常可以为连接到导航视图控制器的应用程序委托定义一个出口。然后就可以使用了

    MyAppDelegate* del = [UIApplication sharedApplication].delegate;
    [del.the_navigation_view_controller pushViewController:...];
    

    【讨论】:

      【解决方案3】:

      你可以从 UIView 获取 UIviewController

      UIViewController *viewC = (UIViewController *)view->_viewDelegate;
      

      【讨论】:

      • _viewDelegate 是私有属性,如果你将应用提交到 AppStore 将无法使用。
      猜你喜欢
      • 2018-04-24
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      • 2013-09-28
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多