话不多说上图
效果就是这样,嘿嘿嘿。
接下来分析一下,层次结构。
首先是segment有一个背景view,颜色为白色,在它之上加入了五个button。
然后在button下面有一个可以移动的横线,横线的宽度是根据button上文字的长度来变化的,颜色和button选中时一样,同时选中时可以切换不同的页面。
上代码分析一下。
- (void)setupTitlesButtonWithTitlesArray:(NSArray *)titlesArray {
CGFloat titlesButtonW = self.frame.size.width / titlesArray.count;
CGFloat titlesButtonH = self.frame.size.height;
for (NSUInteger i = 0; i < titlesArray.count; i ++) {
CYButton *titlesButton = [[CYButton alloc] initWithFrame:CGRectMake(i * titlesButtonW, 0, titlesButtonW, titlesButtonH)];
[titlesButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
[titlesButton setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
[self addSubview:titlesButton];
self.titlesButton = titlesButton;
[titlesButton addTarget:self action:@selector(titlesButtonClick:) forControlEvents:UIControlEventTouchUpInside];
[titlesButton setTitle:titlesArray[i] forState:UIControlStateNormal];
titlesButton.titleLabel.font = [UIFont systemFontOfSize:14];
titlesButton.tag = i;
if (i == 0) {
titlesButton.selected = YES;
self.previousClickButton = titlesButton;
self.firstTitlesWidth = [[titlesButton currentTitle] sizeWithAttributes:@{NSFontAttributeName : titlesButton.titleLabel.font}].width;
}
}
}
这里是计算标题按钮的个数,个数是根据传入的标题数组决定的。
- (void)setupTitleUnderLine {
_titlesUnderLine = [[UIView alloc] initWithFrame:CGRectMake((self.titlesButton.frame.size.width - self.firstTitlesWidth) / 2, self.frame.size.height - 2, self.firstTitlesWidth, 2)];
_titlesUnderLine.backgroundColor = [self.titlesButton titleColorForState:UIControlStateSelected];
[self addSubview:_titlesUnderLine];
}
然后加入下划线。
- (void)titlesButtonClick:(CYButton *)titlesButton {
self.previousClickButton.selected = NO;
titlesButton.selected = YES;
self.previousClickButton = titlesButton;
[UIView animateWithDuration:0.3 animations:^{
CGRect frame = _titlesUnderLine.frame;
frame.size.width = [[titlesButton currentTitle] sizeWithAttributes:@{NSFontAttributeName : titlesButton.titleLabel.font}].width;
_titlesUnderLine.frame = frame;
CGPoint center = _titlesUnderLine.center;
center.x = titlesButton.center.x;
_titlesUnderLine.center = center;
}];
if (_clickTitlesButtonBlock) {
_clickTitlesButtonBlock(titlesButton);
}
}
在监听button的点击事件中,完成button状态的切换以及下划线的变化,用一个回调的block记录当前点击的标题按钮。
最后的效果如下:
资源已上传,附上链接