view中是不能进行UIViewController的push,pop等操作的,若进行跳转操作,一般是用代理,block,通知等实现,那如何实现在ViewController的subView中实现跳转操作呢,其实只要获取该view所在的ViewController即可。
获取view所在UIViewController
UIView+UIViewController.h
#import <UIKit/UIKit.h> @interface UIView (UIViewController) - (UIViewController *)viewController; @end
UIView+UIViewController.m
#import "UIView+UIViewController.h" @implementation UIView (UIViewController) - (UIViewController *)viewController { //通过响应者链,获得view所在的视图控制器 UIResponder *next = self.nextResponder; do { //判断响应者对象是否是视图控制器类型 if ([next isKindOfClass:[UIViewController class]]) { return (UIViewController *)next; } next = next.nextResponder; }while(next != nil); return nil; } @end
or
- (UIViewController *)viewController { // Traverse responder chain. Return first found view controller, which will be the view‘s view controller. UIResponder *responder = self; while ((responder = [responder nextResponder])) if ([responder isKindOfClass: [UIViewController class]]) return (UIViewController *)responder; return nil; }
- (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; }
使用:
在subview中导入 #import "UIView+UIViewController.h"
-(void)viewDidSelect { WebViewController *vc = [[WebViewController alloc] init]; vc.webUrl [email protected]"http://www.baidu.com"; [self.viewController.navigationController pushViewController:vc animated:YES]; }
时间: 2024-12-06 13:31:53