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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值