NSString字体大小计算方法

转载自:http://blog.sojingle.net/


最近在Cocoa学习中遇到一个小问题,就是在一个特定宽度的框中显示几个文字,需要根据宽度来计算字体的大小。后找到方法如下:

NSString有这样一个方法

sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:

Returns the size of the string if it were rendered with the specified constraints, including a variable font size, on a single line.

原型为:

1
2
3
4
5
- (CGSize)sizeWithFont:(UIFont *)font
           minFontSize:(CGFloat)minFontSize
        actualFontSize:(CGFloat *)actualFontSize
              forWidth:(CGFloat)width
         lineBreakMode:(UILineBreakMode)lineBreakMode

使用时,font指定字体和最大字体大小,minFontSize指定最小字体,actualFontSize传递实际大小的引用。width指定总宽度,lineBreakMode指定换行模式。

示例:

1
2
3
4
5
6
7
8
CGFloat fontSize;
NSString *testString = @"All hail Sakuya!";
UIFont *font = [UIFont systemFontOfSize:500];
[testString sizeWithFont:font
             minFontSize:10.0f
          actualFontSize:&fontSize
                forWidth:(self.bounds.size.width)
           lineBreakMode:UILineBreakModeMiddleTruncation];

这段代码计算在一个UIView中显示一个字符串时要用的字体大小。方法的返回值这里没有用上,有用的是这个fontSize。

转载于:https://my.oschina.net/fadoudou/blog/670285

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值