// 设置UISegmentedControl为属性
self.segmentedControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"1",@"2",@"3",@"4", nil]];
self.segmentedControl.frame = CGRectMake(0, 0, WIDTH, 50);
self.segmentedControl.tintColor = [UIColor colorWithRed:0.955 green:0.821 blue:1.000 alpha:1.000];
// 默认第一个为选中
self.segmentedControl.selectedSegmentIndex = 0;
// 选中的颜色
NSDictionary *selected = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:25], NSForegroundColorAttributeName:[UIColor redColor]};
[self.segmentedControl setTitleTextAttributes:selected forState:UIControlStateSelected];
// 没选中时
NSDictionary *unselected = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],NSFontAttributeName:[UIColor redColor]};
[self.segmentedControl setTitleTextAttributes:unselected forState:UIControlStateNormal];
// 点击方法
[self.segmentedControl addTarget:self action:@selector(click:) forControlEvents:UIControlEventValueChanged];
// 铺在View上
[self.view addSubview:self.segmentedControl];
#pragma mark segementedControl的点击方法
- (void)click:(UISegmentedControl *)segmented{
if (segmented.selectedSegmentIndex == 0) {
self.collectionView.contentOffset = CGPointMake(WIDTH * segmented.selectedSegmentIndex, 0);
}else if (segmented.selectedSegmentIndex == 1){
self.collectionView.contentOffset = CGPointMake(WIDTH * segmented.selectedSegmentIndex, 0);
}else if (segmented.selectedSegmentIndex == 2){
self.collectionView.contentOffset = CGPointMake(WIDTH * segmented.selectedSegmentIndex, 0);
}else if (segmented.selectedSegmentIndex == 3){
self.collectionView.contentOffset = CGPointMake(WIDTH * segmented.selectedSegmentIndex, 0);
}
}
// 结束滑动后segmentedControl跟着滑动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
if (scrollView == self.collectionView) {
self.segmentedControl.selectedSegmentIndex = scrollView.contentOffset.x/self.view.frame.size.width;
}
}
// 在里面铺tableViewCell可以试验效果