非推奨のメソッド:NS_DEPRECATED_IOS(2_0、7_0)
- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(NSLineBreakMode)lineBreakMode NS_DEPRECATED_IOS(2_0, 7_0, "Use -boundingRectWithSize:options:attributes:context:");
例
CGSize titleTextSize = [self.titleLabel.text sizeWithFont:self.myLabel.font forWidth:myLabelWidth lineBreakMode:NSLineBreakByTruncatingTail];
新しいアプローチ
使用する :
- (CGRect)boundingRectWithSize:(CGSize)size
options:(NSStringDrawingOptions)options
attributes:(NSDictionary<NSString *,
id> *)attributes
context:(NSStringDrawingContext *)context
例:
// Create a paragraph style with the desired line break mode
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
// Create the attributes dictionary with the font and paragraph style
NSDictionary *attributes = @{
NSFontAttributeName:self.myLabel.font,
NSParagraphStyleAttributeName:paragraphStyle
};
// Call boundingRectWithSize:options:attributes:context for the string
CGRect textRect = [self.countLabel.text boundingRectWithSize:CGSizeMake(widthOfMyLabel, 999999.0f)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
ApppleDocを参照してください