SD_AutoLayout cell自适应高度及方法大全(thuan)

2016年09月02日 16:56:27一缕阳光照四方阅读数 6932

首先SD_AutoLayout布局cell的自适应高度是根据kvc 传值,那么数据类型可以确定了。然后自适应高度和lable原理差不多,都是根据先获取数据来进行建模,也就是不能在重用池中直接给cell.xx = @"";

以下就是书写步骤:

第一步:建立Model类来接受传到cell的属性,

在tableview的重用方法里,传递数据,代码如下

- (MainTableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *string = @"cell";

    MainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:string];


    if (cell == nil ) {

        cell = [[MainTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];

    }

    //在自定义cell中建立一个Model对象的属性,为commentModel(这就是后期要计算高度用到的model的keyPath)

    cell.commentModel = self.modelArray[indexPath.row];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;

}

第二步:在自定义cell中初始化方法里直接初始化对象,并写上布局所需限制条件,但是会根据数据动态变化的控件不能赋值宽,高,要在setmodel中设置,代码如下:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

{

    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

    if (self) {

        [self setup];

    }

    return self;

}

- (void)setup

{

    //头像

    UIImageView *logo = [[UIImageView alloc]init];

    logo.layer.cornerRadius = 45/22.0;

    logo.layer.masksToBounds = YES;

    logo.userInteractionEnabled = YES;

    _logo = logo;

    //标题

    UILabel *lable = [[UILabel alloc]init];

    lable.font = [UIFont systemFontOfSize:12.0];

    lable.textAlignment = NSTextAlignmentLeft;

    lable.textColor = [UIColor orangeColor];

    lable.backgroundColor = [UIColor clearColor];

    _title = lable;

    //圈子图片

    UIImageView *circleImage = [[UIImageView alloc]init];

    circleImage.userInteractionEnabled = YES;

    _circleImage = circleImage;

    //圈子文字

    UILabel *text = [[UILabel alloc]init];

    text.textAlignment = NSTextAlignmentLeft;

    text.font = [UIFont systemFontOfSize:12.0];

    text.textColor = [UIColor blackColor];

    text.backgroundColor = [UIColor lightGrayColor];

    _circleText = text;

    //表情

    UIImageView *emio = [[UIImageView alloc]init];

    emio.userInteractionEnabled = YES;

    _emioImageView = emio;


    //内容

    UILabel *content = [[UILabel alloc]init];

    content.textAlignment = NSTextAlignmentLeft;

    content.font = [UIFont systemFontOfSize:12.0];

    content.textColor = [UIColor blackColor];

    content.backgroundColor = [UIColor clearColor];

    _commentText = content;


    //时间

    UILabel *time = [[UILabel alloc]init];

    time.textAlignment = NSTextAlignmentLeft;

    time.font = [UIFont systemFontOfSize:12.0];

    time.textColor = [UIColor blackColor];

    time.backgroundColor = [UIColor clearColor];

    _commentTime = time;



    //统一添加

    [self.contentView sd_addSubviews:@[_logo,_title,_circleImage,_circleText,_emioImageView,_commentText,_commentTime]];


    _logo.sd_layout

    .widthIs(45)

    .heightIs(45)

    .leftSpaceToView(self.contentView,10)

    .topSpaceToView(self.contentView,10);



    _title.sd_layout

    .topEqualToView(_logo)

    .leftSpaceToView(_logo,10)

    .heightRatioToView(_logo,0.4)

    .rightSpaceToView(self.contentView,10);


    _circleImage.sd_layout

    .leftEqualToView(_title)

    .topSpaceToView(_title,5)

    .widthIs(25)

    .heightEqualToWidth();


    _circleText.sd_layout

    .leftSpaceToView(_circleImage,10)

    .topSpaceToView(_title,5)

    .heightIs(25)

    .rightSpaceToView(self.contentView,10);


    _emioImageView.sd_layout

    .leftEqualToView(_title)

    .topSpaceToView(_circleImage,10)

    .heightIs(90)

    .widthEqualToHeight();



    _commentText.sd_layout

    .leftEqualToView(_title)

    .topSpaceToView(_emioImageView,10)

    .rightSpaceToView(self.contentView,10)

    .autoHeightRatio(0);



    _commentTime.sd_layout

    .leftEqualToView(_title)

    .topSpaceToView(_commentText,10)

    .heightIs(20)

    .rightSpaceToView(self.contentView,10);


}

- (void)setCommentModel:(CommentModel *)commentModel

{

    _commentModel = commentModel;

    _logo.image = [UIImage imageNamed:_commentModel.userLogo];


    _title.text = _commentModel.nickName;

    if (_commentModel.image.length > 0) {

        _circleImage.image  = [UIImage imageNamed:_commentModel.image];    

    }else{

        _circleImage.sd_layout.widthIs(0);

        _circleText.sd_layout.leftEqualToView(_title);

    }

    _circleText.text = _commentModel.title;

    if (_commentModel.emio.length > 0) {


        _emioImageView.image = [UIImage imageNamed:_commentModel.emio];


        _emioImageView.sd_layout.heightIs(140);


    }else{

        _emioImageView.sd_layout.heightIs(0);


    }


    _commentText.text = _commentModel.content;

    if (_commentModel.content.length>0) {


        _commentText.sd_layout.topSpaceToView(_emioImageView,10);


    }else{


        _commentText.sd_layout.topSpaceToView(_emioImageView,0);


    }


    _commentTime.text = _commentModel.addTime;



    // view1使用高度根据子view内容自适应,所以不需要设置高度,而是设置实现高度根据内容自适应

    [self setupAutoHeightWithBottomView:_commentTime bottomMargin:10];


}

第三步:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

/* model 为模型实例, keyPath为 model的属性名,通过 kvc统一赋值接口 */  keypath:比如你要显示的是str,str对应的model的属性是text(model属性名)

    return [self.tableView cellHeightForIndexPath:indexPath model:self.modelArray[indexPath.row] keyPath:@"commentModel" cellClass:[MainTableViewCell class] contentViewWidth:[self cellContentViewWith]];


}

补充:

attributedString

//  --------- attributedString测试:行间距为8 ---------------------------


   NSString *text =@"attributedString测试:行间距为8。彩虹网络卡福利费绿调查开房;卡法看得出来分开了的出口来反馈率打开了房;快烦死了;了;调查开房;;v单纯考虑分离开都快来反馈来看发v离开的积分房积分jdhflgfkkvvm.cm。attributedString测试:行间距为8。彩虹网络卡福利费绿调查开房;卡法看得出来分开了的出口来反馈率打开了房;快烦死了;了;调查开房;;v单纯考虑分离开都快来反馈来看发v离开的积分房积分jdhflgfkkvvm.cm。";

    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStylealloc]init];

    [paragraphStyle setLineSpacing:8];

    UIColor *color = [UIColorblackColor];

    NSAttributedString *string = [[NSAttributedStringalloc]initWithString:textattributes:@{NSForegroundColorAttributeName : color,NSParagraphStyleAttributeName: paragraphStyle}];



    UILabel *label = [UILabel new];

    [self.viewaddSubview:label];

    label.attributedText = string;


    label.sd_layout

    .leftSpaceToView(self.view,10)

    .rightSpaceToView(self.view,10)

    .topSpaceToView(self.view,70)

    .autoHeightRatio(0);


    // 标注lable的text为attributedString

    label.isAttributedContent =YES;

************************************************************************

全部实行方法:

/* 设置距离其它view的间距 */

/** 左边到其参照view之间的间距,参数为“(View 或者 view数组, CGFloat)”  */

@property (nonatomic, copy, readonly) MarginToView leftSpaceToView;

/** 右边到其参照view之间的间距,参数为“(View, CGFloat)”  */

@property (nonatomic, copy, readonly) MarginToView rightSpaceToView;

/** 顶部到其参照view之间的间距,参数为“(View 或者 view数组, CGFloat)”  */

@property (nonatomic, copy, readonly) MarginToView topSpaceToView;

/** 底部到其参照view之间的间距,参数为“(View, CGFloat)”  */

@property (nonatomic, copy, readonly) MarginToView bottomSpaceToView;

/* 设置x、y、width、height、centerX、centerY 值 */

/** x值,参数为“(CGFloat)”  */

@property (nonatomic, copy, readonly) Margin xIs;

/** y值,参数为“(CGFloat)”  */

@property (nonatomic, copy, readonly) Margin yIs;

/** centerX值,参数为“(CGFloat)”  */

@property (nonatomic, copy, readonly) Margin centerXIs;

/** centerY值,参数为“(CGFloat)”  */

@property (nonatomic, copy, readonly) Margin centerYIs;

/** 宽度值,参数为“(CGFloat)”  */

@property (nonatomic, copy, readonly) WidthHeight widthIs;

/** 高度值,参数为“(CGFloat)”  */

@property (nonatomic, copy, readonly) WidthHeight heightIs;

/* 设置最大宽度和高度、最小宽度和高度 */

/** 最大宽度值,参数为“(CGFloat)”  */

@property (nonatomic, copy, readonly) WidthHeight maxWidthIs;

/** 最大高度值,参数为“(CGFloat)”  */

@property (nonatomic, copy, readonly) WidthHeight maxHeightIs;

/** 最小宽度值,参数为“(CGFloat)”  */

@property (nonatomic, copy, readonly) WidthHeight minWidthIs;

/** 最小高度值,参数为“(CGFloat)”  */

@property (nonatomic, copy, readonly) WidthHeight minHeightIs;

/* 设置和某个参照view的边距相同 */

/** 左间距与参照view相同,参数为“(View)”  */

@property (nonatomic, copy, readonly) MarginEqualToView leftEqualToView;

/** 右间距与参照view相同,参数为“(View)”  */

@property (nonatomic, copy, readonly) MarginEqualToView rightEqualToView;

/** 顶部间距与参照view相同,参数为“(View)”  */

@property (nonatomic, copy, readonly) MarginEqualToView topEqualToView;

/** 底部间距与参照view相同,参数为“(View)”  */

@property (nonatomic, copy, readonly) MarginEqualToView bottomEqualToView;

/** centerX与参照view相同,参数为“(View)”  */

@property (nonatomic, copy, readonly) MarginEqualToView centerXEqualToView;

/** centerY与参照view相同,参数为“(View)”  */

@property (nonatomic, copy, readonly) MarginEqualToView centerYEqualToView;

/*  设置宽度或者高度等于参照view的多少倍 */

/** 宽度是参照view宽度的多少倍,参数为“(View, CGFloat)” */

@property (nonatomic, copy, readonly) WidthHeightEqualToView widthRatioToView;

/** 高度是参照view高度的多少倍,参数为“(View, CGFloat)” */

@property (nonatomic, copy, readonly) WidthHeightEqualToView heightRatioToView;

/** 设置一个view的宽度和它的高度相同,参数为空“()” */

@property (nonatomic, copy, readonly) SameWidthHeight widthEqualToHeight;

/** 设置一个view的高度和它的宽度相同,参数为空“()” */

@property (nonatomic, copy, readonly) SameWidthHeight heightEqualToWidth;

/** 自适应高度,传入高宽比值,label可以传0实现文字高度自适应 */

@property (nonatomic, copy, readonly) AutoHeight autoHeightRatio;

/* 填充父view(快捷方法) */

/** 传入UIEdgeInsetsMake(top, left, bottom, right),可以快捷设置view到其父view上左下右的间距  */

@property (nonatomic, copy, readonly) SpaceToSuperView spaceToSuperView;

/** 设置偏移量,参数为“(CGFloat value),目前只有带有equalToView的方法可以设置offset” */

@property (nonatomic, copy, readonly) Offset offset;

@property (nonatomic, weak) UIView *needsAutoResizeView;

@end

#pragma mark - UIView 高度、宽度自适应相关方法

@interface UIView (SDAutoHeightWidth)

/** 设置Cell的高度自适应,也可用于设置普通view内容高度自适应 */

- (void)setupAutoHeightWithBottomView:(UIView *)bottomView bottomMargin:(CGFloat)bottomMargin;

/** 用于设置普通view内容宽度自适应 */

- (void)setupAutoWidthWithRightView:(UIView *)rightView rightMargin:(CGFloat)rightMargin;

/** 设置Cell的高度自适应,也可用于设置普通view内容自适应(应用于当你不确定哪个view在自动布局之后会排布在最下方最为bottomView的时候可以调用次方法将所有可能在最下方的view都传过去) */

- (void)setupAutoHeightWithBottomViewsArray:(NSArray *)bottomViewsArray bottomMargin:(CGFloat)bottomMargin;

/** 更新布局(主动刷新布局,如果你需要设置完布局代码就获得view的frame请调用此方法) */

- (void)updateLayout;

/** 更新cell内部的控件的布局(cell内部控件专属的更新约束方法,如果启用了cell frame缓存则会自动清除缓存再更新约束) */

- (void)updateLayoutWithCellContentView:(UIView *)cellContentView;

/** 清空高度自适应设置  */

- (void)clearAutoHeigtSettings;

/** 清空宽度自适应设置  */

- (void)clearAutoWidthSettings;

@property (nonatomic) CGFloat autoHeight;

@property (nonatomic, readonly) SDUIViewCategoryManager *sd_categoryManager;

@property (nonatomic, readonly) NSMutableArray *sd_bottomViewsArray;

@property (nonatomic) CGFloat sd_bottomViewBottomMargin;

@property (nonatomic) NSArray *sd_rightViewsArray;

@property (nonatomic) CGFloat sd_rightViewRightMargin;

@end

#pragma mark - UIView 设置圆角半径、自动布局回调block等相关方法

@interface UIView (SDLayoutExtention)

/** 自动布局完成后的回调block,可以在这里获取到view的真实frame  */

@property (nonatomic) void (^didFinishAutoLayoutBlock)(CGRect frame);

/** 添加一组子view  */

- (void)sd_addSubviews:(NSArray *)subviews;

/* 设置圆角 */

/** 设置圆角半径值  */

@property (nonatomic, strong) NSNumber *sd_cornerRadius;

/** 设置圆角半径值为view宽度的多少倍  */

@property (nonatomic, strong) NSNumber *sd_cornerRadiusFromWidthRatio;

/** 设置圆角半径值为view高度的多少倍  */

@property (nonatomic, strong) NSNumber *sd_cornerRadiusFromHeightRatio;

/** 设置等宽子view(子view需要在同一水平方向) */

@property (nonatomic, strong) NSArray *sd_equalWidthSubviews;

@end

#pragma mark - UIView 九宫格浮动布局效果

@interface UIView (SDAutoFlowItems)

/** 

 * 设置类似collectionView效果的固定间距自动宽度浮动子view 

 * viewsArray       : 需要浮动布局的所有视图

 * perRowItemsCount : 每行显示的视图个数

 * verticalMargin   : 视图之间的垂直间距

 * horizontalMargin : 视图之间的水平间距

 * vInset           : 上下缩进值

 * hInset           : 左右缩进值

 */

- (void)setupAutoWidthFlowItems:(NSArray *)viewsArray withPerRowItemsCount:(NSInteger)perRowItemsCount verticalMargin:(CGFloat)verticalMargin horizontalMargin:(CGFloat)horizontalMagin verticalEdgeInset:(CGFloat)vInset horizontalEdgeInset:(CGFloat)hInset;

/** 清除固定间距自动宽度浮动子view设置 */

- (void)clearAutoWidthFlowItemsSettings;

/** 

 * 设置类似collectionView效果的固定宽带自动间距浮动子view 

 * viewsArray       : 需要浮动布局的所有视图

 * perRowItemsCount : 每行显示的视图个数

 * verticalMargin   : 视图之间的垂直间距

 * vInset           : 上下缩进值

 * hInset           : 左右缩进值

 */

- (void)setupAutoMarginFlowItems:(NSArray *)viewsArray withPerRowItemsCount:(NSInteger)perRowItemsCount itemWidth:(CGFloat)itemWidth verticalMargin:(CGFloat)verticalMargin verticalEdgeInset:(CGFloat)vInset horizontalEdgeInset:(CGFloat)hInset;

/** 清除固定宽带自动间距浮动子view设置 */

- (void)clearAutoMarginFlowItemsSettings;

@end

#pragma mark - UIView 设置约束、更新约束、清空约束、从父view移除并清空约束、开启cell的frame缓存等相关方法

@interface UIView (SDAutoLayout)

/** 开始自动布局  */

- (SDAutoLayoutModel *)sd_layout;

/** 清空之前的自动布局设置,重新开始自动布局(重新生成布局约束并使其在父view的布局序列数组中位置保持不变)  */

- (SDAutoLayoutModel *)sd_resetLayout;

/** 清空之前的自动布局设置,重新开始自动布局(重新生成布局约束并添加到父view布局序列数组中的最后一个位置)  */

- (SDAutoLayoutModel *)sd_resetNewLayout;

/** 是否关闭自动布局  */

@property (nonatomic, getter = sd_isClosingAotuLayout) BOOL sd_closeAotuLayout;

/** 从父view移除并清空约束  */

- (void)removeFromSuperviewAndClearAutoLayoutSettings;

/** 清空之前的自动布局设置  */

- (void)sd_clearAutoLayoutSettings;

/** 将自身frame清零(一般在cell内部控件重用前调用)  */

- (void)sd_clearViewFrameCache;

/** 将自己的需要自动布局的subviews的frame(或者frame缓存)清零  */

- (void)sd_clearSubviewsAutoLayoutFrameCaches;

/** 设置固定宽度保证宽度不在自动布局过程再做中调整  */

@property (nonatomic, strong) NSNumber *fixedWidth;

/** 设置固定高度保证高度不在自动布局过程中再做调整  */

@property (nonatomic, strong) NSNumber *fixedHeight;

/** 启用cell frame缓存(可以提高cell滚动的流畅度, 目前为cell专用方法,后期会扩展到其他view) */

- (void)useCellFrameCacheWithIndexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableview;

/** 所属tableview(目前为cell专用属性,后期会扩展到其他view) */

@property (nonatomic) UITableView *sd_tableView;

/** cell的indexPath(目前为cell专用属性,后期会扩展到cell的其他子view) */

@property (nonatomic) NSIndexPath *sd_indexPath;

- (NSMutableArray *)autoLayoutModelsArray;

- (void)addAutoLayoutModel:(SDAutoLayoutModel *)model;

@property (nonatomic) SDAutoLayoutModel *ownLayoutModel;

@property (nonatomic, strong) NSNumber *sd_maxWidth;

@property (nonatomic, strong) NSNumber *autoHeightRatioValue;

@end

#pragma mark - UIScrollView 内容竖向自适应、内容横向自适应方法

@interface UIScrollView (SDAutoContentSize)

/** 设置scrollview内容竖向自适应 */

- (void)setupAutoContentSizeWithBottomView:(UIView *)bottomView bottomMargin:(CGFloat)bottomMargin;

/** 设置scrollview内容横向自适应 */

- (void)setupAutoContentSizeWithRightView:(UIView *)rightView rightMargin:(CGFloat)rightMargin;

@end

#pragma mark - UILabel 开启富文本布局、设置单行文本label宽度自适应、 设置label最多可以显示的行数

@interface UILabel (SDLabelAutoResize)

/** 是否是attributedString */

@property (nonatomic) BOOL isAttributedContent;

/** 设置单行文本label宽度自适应 */

- (void)setSingleLineAutoResizeWithMaxWidth:(CGFloat)maxWidth;

/** 设置label最多可以显示多少行,如果传0则显示所有行文字 */

- (void)setMaxNumberOfLinesToShow:(NSInteger)lineCount;

@end

#pragma mark - UIButton 设置button根据单行文字自适应

@interface UIButton (SDExtention)

/*

 * 设置button根据单行文字自适应

 * hPadding:左右边距

 */

- (void)setupAutoSizeWithHorizontalPadding:(CGFloat)hPadding buttonHeight:(CGFloat)buttonHeight;

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,527评论 5 470
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,314评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,535评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,006评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,961评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,220评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,664评论 3 392
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,351评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,481评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,397评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,443评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,123评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,713评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,801评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,010评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,494评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,075评论 2 341