求教如何实现UICollectionViewCell的自适应宽度

 我来答
hswyh
2017-08-12 · 知道合伙人软件行家
hswyh
知道合伙人软件行家
采纳数:268 获赞数:926
武汉市马里欧网络有限公司技术总监 增强现实技术工程师 软件工程系系主任

向TA提问 私信TA
展开全部
#pragma mark — 自定义cell  
  
#import "SelfSizingCollectCell.h"  
#import "Masonry.h"  
#define itemHeight 60  
@implementation SelfSizingCollectCell  
- (instancetype)initWithFrame:(CGRect)frame{  
    self = [super initWithFrame:frame];  
    if (self) {  
        self.contentView.backgroundColor = [UIColor redColor];  
        // 用约束来初始化控件:  
        self.textLabel = [[UILabel alloc] init];  
        self.textLabel.textAlignment =NSTextAlignmentCenter;  
        self.textLabel.backgroundColor = [UIColor greenColor];  
        [self.contentView addSubview:self.textLabel];  
#pragma mark — 如果使用CGRectMake来布局,是需要在preferredLayoutAttributesFittingAttributes方法中去修改textlabel的frame的  
       // self.textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, 30)];  
  
#pragma mark — 如果使用约束来布局,则无需在preferredLayoutAttributesFittingAttributes方法中去修改cell上的子控件l的frame  
        [self.textLabel mas_makeConstraints:^(MASConstraintMaker *make) {  
           // make 代表约束:  
            make.top.equalTo(self.contentView).with.offset(0);   // 对当前view的top进行约束,距离参照view的上边界是 :  
            make.left.equalTo(self.contentView).with.offset(0);  // 对当前view的left进行约束,距离参照view的左边界是 :  
            make.height.equalTo(@(itemHeight/2));                // 高度  
            make.right.equalTo(self.contentView).with.offset(0); // 对当前view的right进行约束,距离参照view的右边界是 :  
        }];  
    }    
    return self;  
}  
#pragma mark — 实现自适应文字宽度的关键步骤:item的layoutAttributes  
- (UICollectionViewLayoutAttributes *)preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes{  
      
    UICollectionViewLayoutAttributes *attributes = [super preferredLayoutAttributesFittingAttributes:layoutAttributes];  
    CGRect rect = [self.textLabel.text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, itemHeight) options:NSStringDrawingTruncatesLastVisibleLine|   NSStringDrawingUsesFontLeading |NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14]} context:nil];  
    rect.size.width +=8;  
    rect.size.height+=8;  
    attributes.frame = rect;  
    return attributes;  
      
}  
@end

#pragma mark — 视图控制器中使用:(关键)
layout.estimatedItemSize = CGSizeMake(20, 60);  // layout约束这边必须要用estimatedItemSize才能实现自适应,使用itemSzie无效

视图控制器.m中源码  
#import "ViewController.h"  
#import "SelfSizingCollectCell.h"  
@interface ViewController () <UICollectionViewDelegate,UICollectionViewDataSource>  
@property (strong, nonatomic) UICollectionView *collection;  
@property (strong, nonatomic) NSArray *dataArr;  
@end  
@implementation ViewController  
#pragma mark --- lazyinit  
- (NSArray *)dataArr{  
    if (!_dataArr) {  
        _dataArr = [NSArray array];  
    }  
    return _dataArr;  
}  
- (void)viewDidLoad {  
    [super viewDidLoad];  
    NSString  *text = @"The UICollectionViewFlowLayout class is a concrete layout object that organizes items into a grid with optional header and footer views for each section. The items in the collection view flow from one row or column (depending on the scrolling direction) to the next, with each row comprising as many cells as will fit. Cells can be the same sizes or different sizesThe UICollectionViewFlowLayout class is a concrete layout object that organizes items into a grid with optional header and footer views for each section. The items in the collection view flow from one row or column.";  
    self.dataArr = [text componentsSeparatedByString:@" "];  
    UICollectionViewFlowLayout  *layout = [[UICollectionViewFlowLayout alloc] init];  
    // 设置具体属性  
    // 1.设置 最小行间距  
    layout.minimumLineSpacing = 20;  
    // 2.设置 最小列间距  
    layout. minimumInteritemSpacing  = 10;  
    // 3.设置item块的大小 (可以用于自适应)  
    layout.estimatedItemSize = CGSizeMake(20, 60);  
    // 设置滑动的方向 (默认是竖着滑动的)  
    layout.scrollDirection =  UICollectionViewScrollDirectionVertical;  
    // 设置item的内边距  
    layout.sectionInset = UIEdgeInsetsMake(10,10,10,10);  
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) collectionViewLayout:layout];  
    self.collection.backgroundColor = [UIColor whiteColor];  
    self.collection.delegate = self;  
    self.collection.dataSource = self;  
    [self.view addSubview:self.collection];  
    [self.collection registerClass:[SelfSizingCollectCell class] forCellWithReuseIdentifier:@"SelfSizingCollectCell"];    
}  
#pragma MARK --- UICollectionViewDelegate  
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{  
    return 1;  
}  
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{  
    return [self.dataArr count];  
}  
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{  
  
    SelfSizingCollectCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SelfSizingCollectCell" forIndexPath:indexPath];  
    cell.textLabel.text = self.dataArr[indexPath.row];  
    return cell;  
}  
- (void)didReceiveMemoryWarning {  
    [super didReceiveMemoryWarning];  
    // Dispose of any resources that can be recreated.  
}  
@end
笑喘是病得抽
2018-08-03 · TA获得超过924个赞
知道大有可为答主
回答量:2140
采纳率:98%
帮助的人:2172万
展开全部
一般都是在设置collectionviewcell尺寸代理方法里将该字符串的长度算出来,设置长度,然后再去更新cell中label的长度,去更新cell中的必须考虑重用问题,所以每次进入cell代理方法都必须在更新一次数据里重新计算label长度,两者都设置好才能保证宽度的自适应
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式