入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

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

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

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

声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
  • 上一篇:没有了
  • 下一篇:没有了
未上传头像