通过UISegmentControl管理页面,结构非常清晰。
不同的页面再由不同的控制器来管理,这样逻辑就更加清晰明了了。
这里用transitionFromViewController切换控制器,有几点好处
- 可以添加动画效果,通过UIViewAnimationOptions
- 对于那些当前暂时不需要显示的subview,只通过addChildViewController把subViewController加进去;需要显示时再调用transitionFromViewController方法。将其添加进入底层的ViewController中。
这样做还有其他的好处:
- 无疑,对页面中的逻辑更加分明了。相应的View对应相应的ViewController。
- 当某个子View没有显示时,将不会被Load,减少了内存的使用。
- 当内存紧张时,没有Load的View将被首先释放,优化了程序的内存释放机制。
主要代码都在MeetingViewController.m文件中,代码如下
//
// MeetingViewController.m
// ScanAndSignIn
//
// Created by shine on 2017/7/7.
// Copyright © 2017年 shine. All rights reserved.
//
#import "MeetingViewController.h"
#import "MeetingPushedViewController.h"
#import "MeetingAttendedViewController.h"
@interface MeetingViewController ()
//管理发布过的会议
@property (nonatomic, strong) MeetingPushedViewController *meettingPushedVC;
//管理参加过的会议
@property (nonatomic, strong) MeetingAttendedViewController *meettingAttendedVC;
//当前的控制器
@property (nonatomic, strong) UIViewController *currentVC;
@end
@implementation MeetingViewController
- (void)viewDidLoad {
[super viewDidLoad];
//
[self setupUI];
}
- (void)setupUI {
//1.设置导航条
NSArray *titleArr = @[@"我发布的",@"我参加的"];
UISegmentedControl *segC = [[UISegmentedControl alloc] initWithItems:titleArr];
segC.tintColor = [UIColor redColor];
[segC addTarget:self action:@selector(didClickSegment:) forControlEvents:UIControlEventValueChanged];
segC.selectedSegmentIndex = 0;
self.navigationItem.titleView = segC;
//2.添加子控制器
//管理发布过的会议的页面
MeetingPushedViewController *meettingPushedVC = [[MeetingPushedViewController alloc] init];
self.meettingPushedVC = meettingPushedVC;
meettingPushedVC.view.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height);
//管理参加过的会议的页面
MeetingAttendedViewController *meettingAttendedVC = [[MeetingAttendedViewController alloc] init];
self.meettingAttendedVC = meettingAttendedVC;
meettingAttendedVC.view.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height);
//3.当前的控制器(默认选择第一个控制器)
self.currentVC = self.meettingPushedVC;
[self.view addSubview:self.meettingPushedVC.view];
[self addChildViewController:meettingPushedVC];
}
- (void)didClickSegment:(UISegmentedControl *)seg {
NSInteger index = seg.selectedSegmentIndex;
switch (index) {
case 0:
[self replaceControl:self.currentVC withNewControl:self.meettingPushedVC];
break;
default:
[self replaceControl:self.currentVC withNewControl:self.meettingAttendedVC];
break;
}
}
- (void)replaceControl:(UIViewController *)oldVC withNewControl:(UIViewController *)newVC {
[self addChildViewController:newVC];
[self transitionFromViewController:oldVC toViewController:newVC duration:1 options:UIViewAnimationOptionTransitionFlipFromLeft animations:nil completion:^(BOOL finished) {
if (finished) {
[newVC didMoveToParentViewController:self];
[oldVC willMoveToParentViewController:nil];
[oldVC removeFromParentViewController];
self.currentVC = newVC;
}else {
self.currentVC = oldVC;
}
}];
}
@end
效果如下: