2013-09-27 94 views
0

我收到了一個警告:「'sizeWithFont:constrainedToSize:lineBreakMode:'已棄用:iOS 7.0以前不推薦使用」 任何人都可以請建議我一種替代方法嗎?sizeWithFont:在iOS 7

- (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; 
} 
+0

[Replacement for deprecated sizeWithFont:in iOS 7?](http://stackoverflow.com/questions/18897896/replacement-for-deprecated-sizewithfont-in-ios -7) – Amar

+0

是的,但那是CGRect,我需要CGFloat。 – Alex

+0

請檢查我的答案 http://stackoverflow.com/questions/18903304/deprecated-in-ios-7-sizewithfont-constrainedtosize-linebreakmode-how-can/19045079#19045079 – svrushal

回答

1

此功能在iOS中棄用7 不是此函數的

sizeWithFont:constrainedToSize: lineBreakMode

使用這一功能,使用

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

boundingRectWithSize:options:attributes:context: 

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

參數 大小 矩形的大小在畫畫。

選項 字符串繪製選項。

屬性 要應用於字符串的文本屬性字典。這些屬性可應用於NSAttributedString對象,但在NSString對象的情況下,這些屬性應用於整個字符串,而不是字符串內的範圍。 上下文

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

+1

此功能可在iOS 7中使用,因此請注意向後兼容性。 – Mercurial

3

另一種方法是:

- (NSSize)sizeWithAttributes:(NSDictionary *)attributes 

你的情況:

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

我用波紋管代碼和它的工作原理:

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

0

備用溶液,用於支撐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]; 
}