在我们平常的开发过程中、在自定义View里面触发点击方法,实现Push到另一个ViewController里面一般通过代理、block、通知等方法
这里介绍一种直接在View里面实现跳转比较方便的一种方法:
#import <UIKit/UIKit.h>
@interface CustomView : UIView
@end
#import "CustomView.h"
#import "ViewPushViewController.h"
@implementation CustomView
//初始化
- (instancetype)init{
if (self = [super init]) {
[self createUI];
}
return self;
}
//懒加载
- (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;
}
//创建UI
- (void)createUI{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[self addSubview:btn];
btn.frame = CGRectMake(100, 100, 100, 50);
btn.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2, [UIScreen mainScreen].bounds.size.height/2);
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btn setTitle:@"点击跳转" forState:UIControlStateNormal];
btn.backgroundColor = [UIColor yellowColor];
[btn addTarget:self action:@selector(pushToNextController) forControlEvents:UIControlEventTouchUpInside];
}
- (void)pushToNextController{
//需要跳转的ViewController
ViewPushViewController *vc = [[ViewPushViewController alloc]init] ;
vc.hidesBottomBarWhenPushed = YES ;
//通过找到的控制器进行跳转
[[self viewController].navigationController pushViewController:vc animated:YES] ;
}
@end
思路:
触发点击事件的控件都是需要加载到控制器所在的view上的,找到控件的事件的响应者链就可以找到视图所加载在的Controller,通过这个controller找到navigationController进行跳转。
主要方法:
OC
- (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;
}
Swift
public func viewController()->UIViewController? {
var nextResponder: UIResponder? = self
repeat {
nextResponder = nextResponder?.next
if let viewController = nextResponder as? UIViewController {
return viewController
}
} while nextResponder != nil
return nil
}
以上方法最好写在分类里面、方便调用
源码下载