iOS 联动

作者: 倚楼听风雨wing | 来源:发表于2016-08-01 18:00 被阅读310次
    连动.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 联动

      本文链接:https://www.haomeiwen.com/subject/aqtfsttx.html