您的位置:首页 > 移动开发 > IOS开发

iOS 根据文字自适应高度

2016-04-28 10:40 302 查看
Objective-C

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
if(tableView == kindTableView)
{
NSInteger section = indexPath.section;

customCell *cell = (customCell *)[tableView dequeueReusableCellWithIdentifier:customCellView];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"customCell" owner:self options:nil];
cell = _customCell;
}
//下面将会用到item
FileListItem * item = [cuArray objectAtIndex:indexPath.row];
cell.textLabel.text = item.name;

//主要是这里
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];
UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cell.textLabel.text sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];

CGRect frame = cell.textLabel.frame;
cell.textLabel.frame = CGRectMake(frame.origin.x, ((labelSize.height + 20)-frame.size.height)/2, frame.size.width, frame.size.height);

}
return cell;

}

//设置cell每行间隔的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//这里的item为什么设置cell时的内容
NSString *cellText = item.name;
UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];

return labelSize.height + 20;
}

swift
//计算文字高度
extension UILabel {
func calculateSize() -> CGFloat {
let options: NSStringDrawingOptions = .UsesLineFragmentOrigin

let string = self.text
let boundingRect = string!.boundingRectWithSize(CGSizeMake(self.frame.size.width, CGFloat.max), options: options, attributes: [NSFontAttributeName:self.font], context: nil)
return boundingRect.height
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios objective-c swift