簡體   English   中英

sizeWithFont:在iOS 7中

[英]sizeWithFont: in iOS 7

我收到警告:“不推薦使用'sizeWithFont:constrainedToSize:lineBreakMode:':iOS 7.0中首先棄用了”。有人可以建議我使用該方法的替代方法嗎?

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Calculate height based on cell content — cell content will stretch appropriately when the height is set
Post *post = self.articleComments[indexPath.row];
CGFloat width = tableView.frame.size.width - 71 - 15;  // Width of comment text area
UIFont *commentFont = [UIFont fontWithName:@"SeroCompPro-Light" size:14];
CGFloat commentTextHeight = [post.text sizeWithFont:commentFont constrainedToSize:CGSizeMake(width, 10000) lineBreakMode:NSLineBreakByWordWrapping].height;

return commentTextHeight + 31 + 37;
}  

替代方法是:

- (NSSize)sizeWithAttributes:(NSDictionary *)attributes

在您的情況下:

[string sizeWithAttributes:@{NSFontAttributeName:[UIFont fontwithName:@"SeroCompPro-Light" size:14]}];

ios 7中不推薦使用此功能。

sizeWithFont:constrainedToSize:lineBreakMode

使用此功能,使用

- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context

 boundingRectWithSize:options:attributes:context:

在當前圖形上下文的指定矩形內,計算並返回使用給定選項和顯示特性繪制的接收器的邊界矩形。

參數size要繪制的矩形的大小。

options字符串繪制選項。

屬性應用於字符串的文本屬性字典。 這些是可以應用於NSAttributedString對象的相同屬性,但是對於NSString對象,這些屬性適用於整個字符串,而不是字符串中的范圍。 上下文

用於接收器的字符串繪制上下文,指定最小比例因子和跟蹤調整。

我用下面的代碼,它的工作原理:

NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@
     {
     NSFontAttributeName: font
     }];

    CGRect rect = [attributedText boundingRectWithSize:(CGSize){size.width, CGFLOAT_MAX}
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];

    result = CGSizeMake(ceilf(rect.size.width), ceilf(rect.size.height));

創建NSAttributedString並使用ceilf方法獲得正確的寬度高度時出現問題

支持IOS7和更低版本的備用解決方案-

CGSize expectedLabelSize;
if ([self respondsToSelector:@selector(sizeWithAttributes:)])
{
    expectedLabelSize = [subTitle sizeWithAttributes:@{NSFontAttributeName:subTitleLabel.font}];
}else{
    expectedLabelSize = [subTitle sizeWithFont:subTitleLabel.font constrainedToSize:subTitleLabel.frame.size lineBreakMode:NSLineBreakByWordWrapping];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM