label在cell中 自适应

来源:互联网 发布:麻辣it网 编辑:程序博客网 时间:2024/06/06 18:48

先在初始化方法中将之创建,并设置numberOfLines = 0

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];    if (self ) { UILabel *tempContent = [[UILabel alloc]initWithFrame:CGRectMake(self.titleLabel.frame.origin.x, CGRectGetMaxY(self.titleLabel.frame),BOUNDS.size.width-self.titleLabel.frame.origin.x-15, 30)];    tempContent.font = [UIFont systemFontOfSize:14.0f];    tempContent.textAlignment = NSTextAlignmentLeft;    tempContent.textColor = CLColor(102, 102, 102);    tempContent.numberOfLines = 0;    [self.contentView addSubview:tempContent];    self.contentLabel = tempContent;    }    return self;}

在添加请求文字的方法中,根据请求到的内容,让其根据内容自适应

- (void)setCellValueWith:(NSDictionary *)param { self.contentLabel.frame = CGRectMake(self.titleLabel.frame.origin.x, CGRectGetMaxY(self.titleLabel.frame),BOUNDS.size.width-self.titleLabel.frame.origin.x-15, 0);        [self.contentLabel sizeToFit];//让内容自适应    }

控制器界面

//得到内容的自适应高度-(CGFloat)contentHeightWithSize:(CGFloat)size width:(CGFloat)width string:(NSString *)string{    //第一个参数:是进行自适应的尺寸  第二个参数:布局格式 第三个参数:字符串的属性列表  第四个忽略    CGRect rect = [string boundingRectWithSize:CGSizeMake(width, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:size]} context:nil];    return rect.size.height;}- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    NSDictionary *dic = [_dataSource objectAtIndex:indexPath.row];   CGFloat contentH = [self contentHeightWithSize:13.0 width:200 string:[dic objectForKey:@"topic"]];    return 60+contentH;}

好了,已经可以实现label的自适应啦,是不是很简单

0 0