1.创建滚动视图
self.titleScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 60)];
_titleScrollView.backgroundColor = [UIColor grayColor];
//设置滚动条
_titleScrollView.showsVerticalScrollIndicator = NO;
_titleScrollView.showsHorizontalScrollIndicator = NO;
_titleScrollView.bounces = NO;
_titleScrollView.contentSize = CGSizeMake(100*self.titlesArray.count,60);
[self.view addSubview:_titleScrollView];
2.添加按钮
for (int i = 0; i <_titlesArray.count; i ++) {
NSString *title = [self.titlesArray objectAtIndex:i];
//创建按钮
UIButton *titleButton = [[UIButton alloc] initWithFrame:CGRectMake(i*100, 0, 100, 60)];
[titleButton setTitle:title forState:UIControlStateNormal];
[titleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//添加按钮事件
[titleButton addTarget:self action:@selector(buttonDidClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.titleScrollView addSubview:titleButton];
}
3.用懒加载创建按钮事件
-(void)buttonDidClicked:(UIButton *)sender{
//判断之前是否选中
if (_lastSelectedButton != nil) {
//将之前选中的按钮状态还原
[_lastSelectedButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
_lastSelectedButton.transform = CGAffineTransformMakeScale(1, 1);
}
//否则 按钮变大变红
[sender setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
sender.transform = CGAffineTransformMakeScale(1.3, 1.3);
//记录当前选中的按钮
_lastSelectedButton = sender;
//处理按钮的滚动
//左边
CGFloat offset = sender.center.x - self.titleScrollView.frame.size.width*0.5;
if (offset < 0) {
offset = 0;
}
//右边
CGFloat maxOffset = self.titleScrollView.contentSize.width - self.titleScrollView.frame.size.width;
if (offset > maxOffset) {
offset = maxOffset;
}
[self.titleScrollView setContentOffset:CGPointMake(offset, 0) animated:YES];
}
4.用懒加载提供按钮数据
#pragma mark ------懒加载------
-(NSArray *)titlesArray{
if (_titlesArray == nil) {
self.titlesArray = @[@"头条",@"体育",@"房产",@"NBA",@"重庆",@"娱乐",@"汽车",@"科技"];
}
return _titlesArray;
}