iOS 聯動

連動.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];
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,245評論 4 61
  • 你看這個世界上有多少形狀各異的男人女人。 我走過嘈雜的馬路,一個低矮的瘦女人叫住我,指著腳下的攤位說:“哎!買個靠...
    流砂阻水閱讀 356評論 2 2
  • 一陽說,最近特郁悶,做什么都很爛,很想死。 我說,你該學習了! 以后的半年時間,我再無他的消息。 再見一陽是在市里...
    荒涼一夢閱讀 317評論 0 1
  • 那年的她十七歲,身穿碎花白裙最好的季節。 那年的她自卑且敏感,別人如花的年華,而她卻像凋落在泥土里的殘花,過得狼狽...
    南涼醬閱讀 261評論 1 1
  • 好種子開花 1今天斗膽跟老大溝通可否調整一下政策,可以讓公司的招生好、客戶好、課程顧問都好,在為客戶爭取更多的福利...
    西紅柿的小姑娘閱讀 314評論 0 0