4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

UILabelの行数を調べる方法

Posted at

UILabelの行数に応じてフォントサイズを変更したりしたかったのでこちらを参考にExtensionとして実装しました
やや使いにくそうでしたので、Swift5に対応してExtensionとして切り出して引数を必要としない形にしました。

環境

Swift 5
Xcode 11.2.1

行数を調べるExtension

行数を計算したいUILabelで利用してください


extension UILabel {
  
  /// 行数を返す
  func lineNumber() -> Int {
    let oneLineRect  =  "a".boundingRect(
      with: self.bounds.size,
      options: .usesLineFragmentOrigin,
      attributes: [NSAttributedString.Key.font: self.font ?? UIFont()],
      context: nil
    )
    let boundingRect = (self.text ?? "").boundingRect(
      with: self.bounds.size,
      options: .usesLineFragmentOrigin,
      attributes: [NSAttributedString.Key.font: self.font ?? UIFont()],
      context: nil
    )
    
    return Int(boundingRect.height / oneLineRect.height)
  }
  
}

参考

UILabel の行数を調べる方法 - Developers.io

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?