牛骨文教育服务平台(让学习变的简单)
博文笔记

iOS中动态计算字符串的长度

创建时间:2015-06-05 投稿人: 浏览次数:3667

在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));  

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。