我正在尝试使用 sizewithattributes 方法计算 uitableview 中 uilabels 的正确高度。但是它返回的高度远低于应有的高度,标签文本被截断,并且从 textwithattributes 返回的高度输出到控制台显示的高度约为 20 - 40,即使对于整段文本也是如此。我已将我的字体大小和字体设置为与方法的属性部分中的 uilabel 相同,并且我将换行模式设置为 uilabel 的自动换行。提前致谢
代码:`
- (UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPath NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSDictionary *message = self.messages[indexPath.row];
NSLog(@"%lu", (long)indexPath.row);
UILabel *nameLabel = (UILabel *)[cell.contentView viewWithTag:20000];
UILabel *messageContent = (UILabel *)[cell.contentView viewWithTag:10000];
UIImageView *image = (UIImageView *)[cell.contentView viewWithTag:30000];
UIButton *replyButton = (UIButton *)[cell.contentView viewWithTag:40000];
replyButton.tag = indexPath.row;
messageContent.text = [message objectForKey"messageContent"];
NSString *content = [message objectForKey"messageContent"];
NSLog(@"Message: %@", content);
NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName"HelveticaNeue" size:17.0f]};
// NSString class method: boundingRectWithSizeptions:attributes:context is
// available only on ios7.0 sdk.
CGRect rect = [content boundingRectWithSize:CGSizeMake(10000, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
CGFloat height = ceilf(rect.size.height);
CGFloat width = ceilf(rect.size.width);
messageContent.frame = CGRectMake(40, 126, width, height);
NSLog(@"Height:%f", messageContent.frame.size.height);
NSLog(@"y: %f", messageContent.frame.origin.y);
NSLog(@"estimated height: %f", height);
nameLabel.text = [message objectForKey"senderName"];
UIImage *senderPic = self.senderPictures[indexPath.row];
image.image = senderPic;
image.layer.cornerRadius = 27.0;
image.layer.masksToBounds = YES;
return cell;
}
`
Best Answer-推荐答案 strong>
你的问题是:
//[content boundingRectWithSize:CGSizeMake(10000, MAXFLOAT)
您指定 100000 pt 作为文本的宽度,我不知道您的 content 字符串包含多少个字符,但我相信您可以轻松地将其显示在一行或两行中是 10000 pt 长。
更好的方法是将文本添加到它的标签读取大小并在需要时更改标签框架:
CGSize labelSize = [self.messageContent.text sizeWithAttributes{NSFontAttributeName:[UIFont systemFontOfSize:self.messageContent.font.pointSize]}];
关于ios - sizewithAttributes 没有为 uilabels 返回正确的高度,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/20764778/
|