标签segmentControl分页显示--->使用UICollectionView

背景交待

项目中好多时候都会用到标签栏,网易新闻/内涵段子/百思不得姐....等等.

IMG_0364.PNG

代码部分

首先定义一个 VIew 把标签栏封装起来,方便以后的使用.

定义一个 View : SegmentControlView.h 中

@property (copy, nonatomic) NSArray *titleArray;// 存放标签的数组
@property (nonatomic, copy) void(^IndexChangeBlock )(NSInteger index);// 定义一个 block 监听点击 进行回传
/** 设置选中第几个*/
- (void)setSelectedSegmentIndex:(NSUInteger)index animated:(BOOL)animated ;

SegmentControlView.m 中

把一个 CollectionView 写成成员变量,

@property (strong, nonatomic) UICollectionView *titleCollectionView;

init中

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.titleCollectionView = [[UICollectionView  alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height) collectionViewLayout:flowLayout];
    
    [self.titleCollectionView registerNib:[UINib nibWithNibName:@"SegmentCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
    
    self.titleCollectionView.delegate = self;
    self.titleCollectionView.dataSource = self;
    self.titleCollectionView.bounces = NO;
    self.titleCollectionView.backgroundColor = [UIColor colorWithHexString:NavColorHexString];
    self.titleCollectionView.showsHorizontalScrollIndicator = NO;
    [self addSubview:self.titleCollectionView];
  }
return self;
}

实现代理-数据源方法

 // 懒加载数据源
 -(NSArray *)titleArray
{
if (!_titleArray) {
    self.titleArray = [NSArray  array];
    
    }
  return _titleArray;
}

- (void)setSelectedSegmentIndex:(NSUInteger)index animated:(BOOL)animated {
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
[self.titleCollectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionCenteredHorizontally];
}
#pragma mark - <UICollectionViewDelegate,UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
NSLog(@"%ld",self.titleArray.count);
return self.titleArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    SegmentCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.title = self.titleArray[indexPath.row];

    return cell;
}

//  根据文字长度计算 size
- (CGSize )collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
CGSize itemSize = [self.titleArray[indexPath.row] getStringSize:[UIFont systemFontOfSize:14] width:self.bounds.size.width];
return CGSizeMake(itemSize.width + 20, itemSize.height + 20);
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.IndexChangeBlock) {
    self.IndexChangeBlock(indexPath.row);
    }
    [self.titleCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
  }

/**
 *  计算 label 高度的一般的自适应
 *
 *  @param font  字号
 *  @param width 宽度
 *
 *  @return  size
 */
- (CGSize)getStringSize:(UIFont*)font width:(CGFloat)width
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self];
    NSDictionary *attrSyleDict = [[NSDictionary alloc] initWithObjectsAndKeys:
                              font, NSFontAttributeName,
                              nil];
    [attributedString addAttributes:attrSyleDict
                          range:NSMakeRange(0, self.length)];
    CGRect stringRect = [attributedString boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
                                                   options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                                   context:nil];

    return stringRect.size;
}

自定义一个 xib cell

BD3ECA67-8C06-4BB2-940E-95ED8559040A.png

一个 label + ImageView 都是居中 (根据自己实际项目需求适当调整,我这个仅是选中状态有一个白色边框)

cell .m 中


588C5E36-340E-4396-9980-6415095EB375.png

cell.h 中

FB3FF3D4-AA3F-4C2B-AB90-F87AACBF44F6.png

使用:

怎么使用呢? 很简单把刚才创建的四个文件导入你的工程就可以使用了

![Uploading 屏幕快照 2016-04-11 下午5.26.27_802064.png . . .]

然后在你的 viewDidLoad 中 初始化

    self.automaticallyAdjustsScrollViewInsets = NO;
CGFloat screen_width = self.view.bounds.size.width;


_titleSegView = [[SegmentControlView alloc] initWithFrame:CGRectMake(0, 64, screen_width, 55)];
self.titleSegView.backgroundColor = [UIColor blueColor];
[self.view addSubview:_titleSegView];

self.titleSegView.titleArray = @[@"标签1",@"标签2",@"标签3",@"标签4",@"标签5",@"标签6",@"标签7",];
[self.titleSegView setSelectedSegmentIndex:0 animated:YES];
__weak typeof(self) weakSelf = self;
self.titleSegView.IndexChangeBlock = ^(NSInteger index){// 点击切换
    CGPoint offset = weakSelf.mainScrollview.contentOffset;
    offset.x = index * screen_width;
    [weakSelf.mainScrollview setContentOffset:offset animated:YES];
};
// 创建一个 scrollView 
_mainScrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_titleSegView.frame), screen_width, self.view.bounds.size.height - 110)];
self.mainScrollview.pagingEnabled = YES;
self.mainScrollview.showsHorizontalScrollIndicator = NO;
self.mainScrollview.showsVerticalScrollIndicator = NO;
self.mainScrollview.contentSize = CGSizeMake(screen_width * self.titleSegView.titleArray.count, self.view.bounds.size.height - 110);
self.mainScrollview.delegate = self;
self.mainScrollview.bounces = NO;
[self.view addSubview:_mainScrollview];

for (NSInteger i=0  ;i < self.titleSegView.titleArray.count ; i ++) {
    UILabel *label1 = [UILabel new];
    label1.frame = CGRectMake(i *screen_width, 50, 100, 100);
    label1.backgroundColor = [UIColor redColor];
    [self.mainScrollview addSubview:label1];
}

实现 scrollView 的代理方法

#pragma mark - UIScrollViewDelegate
// 滑动切换
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
CGFloat pageWidth = scrollView.frame.size.width;
NSInteger page = scrollView.contentOffset.x / pageWidth;
[self.titleSegView setSelectedSegmentIndex:page animated:YES];
}

运行的效果图

DB211.gif

代码下载

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,486评论 25 709
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,735评论 4 61
  • 教室空空的,却装满了暖暖 的回忆 那年的夏季,我们把欢笑都 留在这里 课桌旁的你,嘴角扬上去特 别的美丽 像彩虹般...
    时光划破青春_cc51阅读 1,135评论 0 2
  • 前情回顾 忤逆完我赶紧摁断电话,不然又得被老妈絮絮叨叨数落半个小时,她不心疼话费,我还看不得中国移动平白无故赚那么...
    狗一样的污姐阅读 1,756评论 0 0
  • 过程很痛苦,结果很无奈。 今天调试程序点击按钮调起系统相机,结果无论多少次,都是直接崩溃,抛出异常如下: 因为我已...
    逐水而上阅读 8,283评论 0 2

友情链接更多精彩内容