今天要寫(xiě)個(gè)聊天頁(yè)面,需要用到可以滾動(dòng)的顯示方式,滑動(dòng)頁(yè)面切換控制器,點(diǎn)擊UISegmentedControl同樣切換界面.UISegmentedControl不常用,折騰一個(gè)小時(shí),總算可以用了,
直接貼代碼,挺簡(jiǎn)單的.
// 獲取屏幕寬高#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 - 導(dǎo)航欄
-(void)createNav{
_navBgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH, 64)];
[self.view addSubview:_navBgView];
_navBgView.backgroundColor = [UIColor orangeColor];
#pragma mark - 分頁(yè)控制器
NSArray * items = @[@"消息",@"聯(lián)系人",@"動(dòng)態(tài)"];
_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];
}
//分頁(yè)
_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{
// 計(jì)算當(dāng)前在第幾頁(yè)
_pageControl.currentPage = (NSInteger)(scrollView.contentOffset.x / [UIScreen mainScreen].bounds.size.width);
_segmentControl.selectedSegmentIndex = _pageControl.currentPage;
}
#pragma mark - 分頁(yè)事件
-(void)changeView:(UISegmentedControl *)sgmentC{
NSInteger index = sgmentC.selectedSegmentIndex;
NSLog(@"%ld",index);
//改變當(dāng)前的顯示范圍
[_scrollView setContentOffset:CGPointMake(index*SCREEN_WIDTH, 0)];
}
效果圖