动态改变Cell的高度
1.利用tableView代理方法的返回值决定每一行cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
2.UIFont
// 返回字体的行高
* [UIFont systemFontOfSize:10].lineHeight
3.动态改变cell的高度例子
#pragma mark - 返回每一行cell的高度 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { // 1.取出这行微博的内容 Status *s = _statuses[indexPath.row]; // 2.计算微博内容大小占据的高度 NSString *text = s.text; CGFloat textHeight = [text sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(250,MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping].height; // sizeWithFont: 根据字体来算text的宽高 // constrainedToSize: 限制算出来的文集的宽度和高度 这里限制宽度为250个像素点 // lineBreakMode: 换行的模式 // 3.计算昵称的高度 CGFloat screenNameHeight = [UIFont systemFontOfSize:13].lineHeight; // 4.cell的高度 微博内容的高度 + 微博昵称的高度 + cell内部label之间的高度 CGFloat cellHeight = screenNameHeight +textHeight +35; // 设置cell的高度 return cellHeight < 75 ? 75 : cellHeight; }
NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:14]}; CGRect rect = [textToMeasure boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
iOS7中用以下方法 - (CGSize)sizeWithAttributes:(NSDictionary *)attrs; 替代过时的iOS6中的- (CGSize)sizeWithFont:(UIFont *)font 方法 // iOS7_API_根据文字 字数动态确定Label宽高 // 设置Label的字体 HelveticaNeue Courier UIFont *fnt = [UIFont fontWithName:@"HelveticaNeue" size:24.0f]; _nameLabel.font = fnt; // 根据字体得到NSString的尺寸 CGSize size = [_nameLabel.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil]]; // 名字的H CGFloat nameH = size.height; // 名字的W CGFloat nameW = size.width _nameLabel.frame = CGRectMake(0, 0, nameW,nameH);