在view中实现UIViewController的跳转 By H.L
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; }
其它 iOS 获取当前正在显示的ViewController
使用:
在subview中导入 #import "UIView+UIViewController.h"
-(void)viewDidSelect { WebViewController *vc = [[WebViewController alloc] init]; vc.webUrl =@"http://www.baidu.com"; //如果VC 是添加在Nav 上的 用 [self.viewController.navigationController pushViewController:ViewController animated:YES]; //else 如果没有添加用 [self presentModalViewController: ViewController animated:YES]; }
作者:SIBU iOS DEV
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.