一個簡易的選項卡鏤空的分段控制器:
內(nèi)部使用UICollectionView實現(xiàn)近忙,可以計算出當(dāng)前顯示的控制器視圖的下標(biāo)寸认,以及將要顯示控制器視圖的下標(biāo)冒黑。底部選項紅線隨title寬度變化护昧。
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (scrollView == self.contentCollectionView) {
// 計算將要顯示的控制器視圖下標(biāo)
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");
// 計算已經(jīng)顯示的控制器視圖下標(biāo)
self.selectedIndex = (NSInteger)(scrollView.contentOffset.x / scrollView.frame.size.width);
self.willSelectIndex = self.selectedIndex;
}
}