为什么view在,viewController不在(因为viewController被销毁所以不能处理业务逻辑)?
1.只添加了控制器的view并没有添加控制器,控制器没有强引用被销毁
解决方案:
1.在顶层ViewController设置强引用(强烈不推荐)
2.使用父子控制器(UIViewController管理子UIViewController)
ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
ScoietyViewController *scoietyVc = [[ScoietyViewController alloc] init];
scoietyVc.title = @"社会";
[self addChildViewController:scoietyVc];
TopLineViewController *topLineVc = [[TopLineViewController alloc] init];
topLineVc.title = @"头条";
[self addChildViewController:topLineVc];
HotViewController *hotVc = [[HotViewController alloc] init];
hotVc.title = @"热点";
[self addChildViewController:hotVc];
NSInteger count = self.titleContainView.subviews.count;
for (int i = 0; i < count; i++) {
UIButton *btn = self.titleContainView.subviews[i];
UIViewController *vc = self.childViewControllers[i];
[btn setTitle:vc.title forState:UIControlStateNormal];
- (IBAction)showChildVcView:(UIButton *)sender {
[self.containView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
UIViewController *vc = self.childViewControllers[sender.tag];
vc.view.backgroundColor = sender.backgroundColor;
vc.view.frame = self.containView.bounds;
[self.containView addSubview:vc.view];
ViewController.m
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
ChildViewController *childVc = [[ChildViewController alloc] init];
childVc.view.backgroundColor = [UIColor greenColor];
childVc.view.frame = CGRectMake(50, 50, 200, 200);
[self.view addSubview:childVc.view];
[self addChildViewController:childVc];
ChildViewController.m
@implementation ChildViewController
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
NSLog(@"点击了子控制器的view %@",self.navigationController);
UIViewController *vc = [[UIViewController alloc] init];
vc.view.backgroundColor = [UIColor redColor];