一个简易的选项卡镂空的分段控制器:
内部使用UICollectionView实现,可以计算出当前显示的控制器视图的下标,以及将要显示控制器视图的下标。底部选项红线随title宽度变化。
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (scrollView == self.contentCollectionView) {
// 计算将要显示的控制器视图下标
NSInteger contentOffset_x = (NSInteger)ABS(self.selectedIndex * scrollView.frame.size.width - scrollView.contentOffset.x);
if (scrollView.contentOffset.x < self.selectedIndex * scrollView.frame.size.width) { // ←
self.willSelectIndex = self.selectedIndex - ceil(contentOffset_x/scrollView.frame.size.width);
}else { // →
self.willSelectIndex = self.selectedIndex + ceil(contentOffset_x/scrollView.frame.size.width);
}
self.segmentBar.selectedItemContentOffset_x = scrollView.contentOffset.x;
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[self performSelector:@selector(scrollViewDidEndScrollingAnimation:) withObject:self.contentCollectionView afterDelay:.1];
}
}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
if (scrollView == self.contentCollectionView) {
[NSObject cancelPreviousPerformRequestsWithTarget:self];
NSLog(@"scroll end");
// 计算已经显示的控制器视图下标
self.selectedIndex = (NSInteger)(scrollView.contentOffset.x / scrollView.frame.size.width);
self.willSelectIndex = self.selectedIndex;
}
}