連動.gif
實現思路##
在做一個頁面之前,一定要先思考好應該如何寫,方法用對了是可以省很多事的.對于這樣的一個連動的頁面.我采取的方法是使用兩個UICollectionView
和若干個UITableView
.頂部頭是一個UICollectionView
,下面滾動頁是一個UICollectionView
,滾動頁里面的每一個cell都包含一個UITableView
.滾動的橫條用的是CALayer
,因為CALayer
改變位置后自帶隱式動畫,可以省去寫動畫的代碼.
頭部視圖WYTradeHeaderView.h
/// 滾動到了第幾頁
- (void)slideToIndex:(NSInteger)index;
/// 滾動到幾點幾
- (void)slideToRatio:(CGFloat)ratio;
頭部視圖WYTradeHeaderView.m
其中的CELL_WIDTH
代表的是頭部cell的寬度,具體在項目中由自己設置.
#pragma mark - private
- (void)slideToIndex:(NSInteger)index {
CGRect slideRect = _slideLayer.frame;
slideRect.origin.x = index * CELL_WIDTH;
_slideLayer.frame = slideRect;
self.selectedCell = (WLTradeHeadCell *)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
}
- (void)slideToRatio:(CGFloat)ratio {
CGRect slideRect = _slideLayer.frame;
slideRect.origin.x = ratio * CELL_WIDTH;
[CATransaction begin];
[CATransaction setDisableActions:YES];
_slideLayer.frame = slideRect;
[CATransaction commit];
self.selectedCell = (WLTradeHeadCell *)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:ratio + 0.5 inSection:0]];
}
#pragma mark - setter
- (void)setSelectedCell:(WLTradeHeadCell *)selectedCell {
_selectedCell.nameLabel.textColor = WLColorLightGray_text;
selectedCell.nameLabel.textColor = WLColorBlue;
_selectedCell = selectedCell;
}
底部UICollectionView
的主要操作,監聽底部視圖的滾動,然后實時更改頭部視圖,讓其實現聯動
- (void)viewDidLoad {
[super viewDidLoad];
[self prepareHeaderView];
}
- (void)prepareHeaderView {
__weak typeof(_collectionView) weakCollectionView = _collectionView;
_headView = [WLTradeHeadView tradeHeadViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45) onClick:^(NSInteger index) {
[weakCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}];
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
[_headView slideToRatio:scrollView.contentOffset.x / SCREEN_WIDTH];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
self.currentPage = scrollView.contentOffset.x / SCREEN_WIDTH;
}
#pragma mark - setter
- (void)setCurrentPage:(NSInteger)currentPage {
_currentPage = currentPage;
[_headView slideToIndex:currentPage];
}