使用场景
有的时候,比如在当前的页面加载一个游戏,跳转到其他页面显示新闻。会导致之前的页面暂停。因为需要页面不跳转的方式显示新的页面内容。
使用
@interface SecondViewController : UIViewController
@property (nonatomic, copy) void (^goBack)(void);
@end
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor blueColor];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setTitle:@"返回" forState:UIControlStateNormal];
[self.view addSubview:btn];
btn.frame = CGRectMake(20, 50, 100, 40);
btn.backgroundColor = [UIColor grayColor];
[btn addTarget:self action:@selector(clickGoBack) forControlEvents:UIControlEventTouchUpInside];
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
NSLog(@"%@ %s",self, __func__);
}
- (void)clickGoBack{
if(self.goBack){
self.goBack();
}
}
-(void)dealloc{
NSLog(@"%@ %s",self, __func__);
}
#import "ViewController.h"
#import "SecondViewController.h"
@interface ViewController ()
@property (nonatomic, strong) SecondViewController *secondVC;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setTitle:@"下一页" forState:UIControlStateNormal];
[self.view addSubview:btn];
btn.frame = CGRectMake(20, 50, 100, 40);
btn.backgroundColor = [UIColor grayColor];
[btn addTarget:self action:@selector(clickGoNext1) forControlEvents:UIControlEventTouchUpInside];
}
- (void)clickGoNext1{
SecondViewController *vc1 = [SecondViewController new];
[self addChildViewController:vc1];
[self.view addSubview:vc1.view];
__weak typeof(self) weakSelf = self;
vc1.goBack = ^{
__strong typeof(self) self = weakSelf;
UIViewController *secondVC = [self.childViewControllers firstObject];
[secondVC.view removeFromSuperview];
[secondVC removeFromParentViewController];
};
}
- (void)clickGoNext{
__weak typeof(self) weakSelf = self;
SecondViewController *vc = [SecondViewController new];
[self.view addSubview:vc.view];
self.secondVC = vc;
self.secondVC.goBack = ^{
__strong typeof(self) self = weakSelf;
[self.secondVC.view removeFromSuperview];
self.secondVC = nil;
};
}
@end
其中clickGoNext
的方式是我们手动添加一个引用,而clickGoNext1
则是通过系统方法帮我们添加了一个引用。本身并无好差之分,可以根据自己的实际情况选择。
另外,上面两种方式都会影响View的生命周期函数被调用viewWillAppear
。
如果页面无需关系这些函数,也可以不用视图控制器,直接初始化一个UIView添加到当前的页面中。