在iOS7以下动态算一个string的size的时候可以用sizeWithFont
- (CGSize)sizeWithFont:(UIFont *)font
具体应用:
CGSize statuseStrSize = [lcsstring sizeWithFont:string.font];
或者
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode;
具体应用:
CGSize statuseStrSize = [lcsstring sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:theLabel.frame.size lineBreakMode:NSLineBreakByCharWrapping];
但是在ios7以后苹果放弃这个方法,完全可以找到同样效果的方法,方法也很简单
CGSize size = [self.statusLabel.text sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:17.0f]}];
CGSize statuseStrSize = CGSizeMake(ceilf(size.width), ceilf(size.height));
现在的方法更强大,可以加入了属性字典,例如font ,color,下划线,背景色等
- (CGSize)sizeWithAttributes:(NSDictionary *)attrs
具体应用:
CGSize size = [@"这个是测试字段” sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:18.0f],NSStrokeColorAttributeName: [UIColor greenColor], NSForegroundColorAttributeName:[UIColor greenColor]}];
CGSize statuseStrSize = CGSizeMake(ceilf(size.width), ceilf(size.height));
NSLog(@"%@",NSStringFromCGSize(statuseStrSize));
原文地址:http://blog.csdn.net/lu_ca/article/details/46375279