今天要写个聊天页面,需要用到可以滚动的显示方式,滑动页面切换控制器,点击UISegmentedControl同样切换界面.UISegmentedControl不常用,折腾一个小时,总算可以用了,
直接贴代码,挺简单的.
// 获取屏幕宽高#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height@interface ViewController ()@property(nonatomic,strong)UIView * navBgView;
@property(nonatomic,strong)UIScrollView * scrollView;
@property(nonatomic,strong)UIPageControl * pageControl;
@property(nonatomic,strong)UISegmentedControl * segmentControl;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationController.navigationBarHidden = YES;
[self createNav];
[self createUI];
}
#pragma mark - 导航栏
-(void)createNav{
_navBgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH, 64)];
[self.view addSubview:_navBgView];
_navBgView.backgroundColor = [UIColor orangeColor];
#pragma mark - 分页控制器
NSArray * items = @[@"消息",@"联系人",@"动态"];
_segmentControl = [[UISegmentedControl alloc]initWithItems:items];
[_navBgView addSubview:_segmentControl];
_segmentControl.frame = CGRectMake(SCREEN_WIDTH*0.5 - 75, 27, 150, 30);
_segmentControl.selectedSegmentIndex = 0;
_segmentControl.tintColor = [UIColor whiteColor];
[_segmentControl addTarget:self action:@selector(changeView:) forControlEvents:UIControlEventValueChanged];
}
#pragma mark - UI
-(void)createUI{
_scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT)];
[self.view addSubview:_scrollView];
_scrollView.contentSize = CGSizeMake(SCREEN_WIDTH*3, SCREEN_HEIGHT);
_scrollView.bounces = NO;
_scrollView.pagingEnabled = YES;
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.delegate = self;
_scrollView.backgroundColor = [UIColor whiteColor];
NSArray * arr = @[@"AViewController",@"BViewController",@"CViewController"];
for (int i = 0; i< arr.count; i++) {
Class class = NSClassFromString(arr[i]);
UIViewController * viewCon = [[class alloc]init];
viewCon.view.frame = CGRectMake(SCREEN_WIDTH*i, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64);
[_scrollView addSubview:viewCon.view];
}
//分页
_pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/3, 300, 0, 0)];
_pageControl.numberOfPages = 3;
_pageControl.pageIndicatorTintColor = [UIColor whiteColor];
_pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
[self.view addSubview:_pageControl];
}
#pragma mark - scrollView delegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
// 计算当前在第几页
_pageControl.currentPage = (NSInteger)(scrollView.contentOffset.x / [UIScreen mainScreen].bounds.size.width);
_segmentControl.selectedSegmentIndex = _pageControl.currentPage;
}
#pragma mark - 分页事件
-(void)changeView:(UISegmentedControl *)sgmentC{
NSInteger index = sgmentC.selectedSegmentIndex;
NSLog(@"%ld",index);
//改变当前的显示范围
[_scrollView setContentOffset:CGPointMake(index*SCREEN_WIDTH, 0)];
}
效果图