类似新闻首页标签的滚动与内容联动(对上一篇介绍的流畅度进行调整)

2017-06-15  本文已影响143人  皮乐皮儿

ps:前两天写了一篇类似新闻首页标签滚动与定位的文章,对于需求新闻类的标签滚动与内容联动来说,只要稍加修改,基本上都能够完成,上一篇文章采用的是collectionView与scrollView的联动,但是在我测试过程中发现两个问题:1.快速滚动内容视图,有时候顶部标签栏会出现标签和内容不对应的问题,这是在暴力测试下才有的 2.如果有强迫症的用户,会发现,在滚动标签栏的时候体验有些不好,如果滚动幅度小,有时候需要滚动好几下才能滚动到下一个标签,这样的体验也是硬伤,鉴于此,在原来的实现方式上我试过调整,但是没有成功,如果有哪位同伴弄出来了,麻烦贴出来,大家都可以共同学习,将这块类似的需求尽量做到完善。

所以,在技术老大的指引下,搜到了一个Nick Lock wood写的一个库,叫SwipeView,我接入到自己的项目中发现,滚动起来非常的流畅,下面就来说说我的具体实现,主要是对于顶部标签栏的实现,内容视图的实现采用的还是之前的方式,如果又兴趣的同伴,可以将内容视图呈现也采用SwipeView的方式,因为之前的方式没有采用复用tableView,而swipeView也许可以解决这方面的性能问题。

标签栏的定制

这里主要展示引入SwipeView之后的标签定制

 self.swipeView = [[SwipeView alloc] initWithFrame:self.bounds];
    self.swipeView.backgroundColor = [UIColor whiteColor];
    self.swipeView.alignment = SwipeViewAlignmentCenter;
    self.swipeView.pagingEnabled = YES;
    self.swipeView.itemsPerPage = 1;
    self.swipeView.truncateFinalPage = YES;
    self.swipeView.dataSource = self;
    self.swipeView.delegate = self;
    [self addSubview:self.swipeView];

它的实现方式很有点类似tableView的使用味道,下面看数据源方法和代理方法:

- (NSInteger)numberOfItemsInSwipeView:(SwipeView *)swipeView {
    
    return self.dataSource.count;
}

- (CGSize)swipeViewItemSize:(SwipeView *)swipeView {
    
    return CGSizeMake(self.frame.size.width / 3, self.frame.size.height);
}

- (UIView *)swipeView:(SwipeView *)swipeView viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view {
    if (!view) {
        view = [[NSBundle mainBundle] loadNibNamed:@"YGTagView" owner:self options:nil][0];
    }
    ((YGTagView *)view).tagTitle = self.dataSource[index];
    
    ((YGTagView *)view).tagSelected = (self.currentIndex == index);
    return view;
}

- (void)swipeView:(SwipeView *)swipeView didSelectItemAtIndex:(NSInteger)index {
    
    self.scrollSwipeView = NO;
    
    [self updateScrollOffsetWith:index];
    [self triggerTopItemRequestWith:index];
    
}

- (void)swipeViewWillBeginDragging:(SwipeView *)swipeView {
    
    self.scrollSwipeView = YES;
}

- (void)swipeViewDidEndDecelerating:(SwipeView *)swipeView {
    if (!self.scrollSwipeView) {
        return;
    }
    [self updateScrollOffsetWith:swipeView.currentItemIndex];
    [self triggerTopItemRequestWith:swipeView.currentItemIndex];
}

改变标签的位置代码如下:

- (void)updateScrollOffsetWith:(NSInteger)itemIndex {
    
    self.scrollSwipeView = NO;
    
    if (self.currentIndex == itemIndex) {
        return;
    }
    YGTagView *oldView = (YGTagView *)[self.swipeView itemViewAtIndex:self.currentIndex];
    oldView.tagSelected = NO;
    
    YGTagView *currentView = (YGTagView *)[self.swipeView itemViewAtIndex:itemIndex];
    currentView.tagSelected = YES;
    self.currentIndex = itemIndex;
    [self.swipeView scrollToItemAtIndex:itemIndex duration:0.2];
}

换成这种方式之后,不仅体验上更加流畅,而且代码也减少很多,具体的体验可以下载源码体验一下,对于这个库,我还没来得及细细学习,有想要研究的同学可以去开头给出的地址链接中下载学习一下,真的很不不错哦。

上一篇下一篇

猜你喜欢

热点阅读