实现这个渐变导航条的功能,需要拿到前后两个button,所以在创建button的时候要把它们加入到一个可变的数组中。
// 滚动中调用
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat offsetX = scrollView.contentOffset.x;
// 取出左右两个button的index
NSInteger leftIndex = offsetX / ZHJScreenW;
NSInteger rightIndex = leftIndex + 1;
// 取出左边的button
UIButton *leftButton = self.buttons[leftIndex];
// 取出右边的button,考虑到在最右边的时候不用再滑动了,所以要判断下
UIButton *rightButton = nil;
if (rightIndex < self.buttons.count) {
rightButton = self.buttons[rightIndex];
}
// 取出左边的缩放值
CGFloat scaleR = offsetX / ZHJScreenW - leftIndex;
// 取出右边的缩放值
CGFloat scaleL = 1 - scaleR;
// maxTitleScale = 1.3 是最大缩放大小
CGFloat transScale = maxTitleScale - 1;
leftButton.transform = CGAffineTransformMakeScale(scaleL * transScale + 1, scaleL * transScale + 1);
rightButton.transform = CGAffineTransformMakeScale(scaleR * transScale + 1, scaleR * transScale + 1);
// 用rgb来实现颜色的渐变
UIColor *rightColor = [UIColor colorWithRed:scaleR green:scaleR blue:scaleR alpha:1];
UIColor *leftColor = [UIColor colorWithRed:scaleL green:scaleL blue:scaleL alpha:1];
[leftButton setTitleColor:leftColor forState:UIControlStateNormal];
[rightButton setTitleColor:rightColor forState:UIControlStateNormal];
// 设置指示器的位置
// 算出button的宽度
CGFloat buttonW = (self.view.width - 100) / 3.0;
// 设置动画
self.indicator.transform = CGAffineTransformMakeTranslation(buttonW * (offsetX / ZHJScreenW), 0);
}