您的位置:首页 > 产品设计 > UI/UE

IOS_UITableViewCell(UITabel)自动适应Row高

2016-03-09 17:59 387 查看
ViewController.m

在UITableView里面有一个协议叫< UITableViewDataSource>

里面有一个方法:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//返回行的高度
return 0;
}


主要代码:

ViewController.m

协议的方法

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:Cell forIndexPath:indexPath];
NSDictionary *dic=_dataArray[indexPath.row];
cell.textLabel.text=dic[@"text"];
cell.textLabel.numberOfLines=0;//自动适应label高和宽
cell.textLabel.font=[UIFont systemFontOfSize:15];//设置label文字大小
return cell;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dic=_dataArray[indexPath.row];//从数组里面取出字典
NSString *string=dic[@"text"];//从字典取出字符串
/*
得到label在Row的CGRect
*/
CGRect fram=[string boundingRectWithSize:CGSizeMake(UISCREEN_W-30, SHRT_MAX)                               options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}
context:nil];

if (fram.size.height>30)//判断label高度大于30
{
return fram.size.height+10;//如果大于30给他足够的高度
}
else
{
return 30;//如果不大于30就说明只有一行
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: