LoginSignup
18
18

More than 5 years have passed since last update.

非推奨になった sizeWithFont:constrainedToSize:lineBreakMode を置き換える

Posted at

最大行数が指定された UILabel の実際の高さを求めたい時などに sizeWithFont:constrainedToSize:lineBreakMode が便利でしたが、非推奨になりました。
置き換え方法を考えていたところ stackoverflow にサンプルが示されていたのでメモ

Before

NSString *text = @"あのイーハトーヴォのすきとおった風";
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:14.0f]
               constrainedToSize:CGSizeMake(200.0f, 36.0f)
                   lineBreakMode:NSLineBreakByTruncatingTail];

After

NSString *text = @"あのイーハトーヴォのすきとおった風";
CGSize size = [text boundingRectWithSize:CGSizeMake(200.0f, 36.0f)
                                 options:NSStringDrawingUsesLineFragmentOrigin
                              attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0f]}
                                 context:nil].size;

boundingRectWithSize:options:attributes:context: で CGRect を求めてから CGSize を抽出すればいいんですね。

注意点

boundingRectWithSize:options:attributes:context: は iOS7 以上が必要。なのでそれよりも古い環境もサポートするには条件分岐して併記する必要あり。

18
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
18