xyk blog

最近は iOS 開発の記事が多めです。

Swift で UILabel、UITextView の行間を広げる

検証環境:
Xcode 12
Swift 5.3

UILabel や UITextView で複数行のテキストを表示する場合、デフォルトでは行間がかなり狭い。
行の間隔を広げるには、UILabel、UITextView のどちらもattributedTextプロパティにNSAttributedString.KeyparagraphStyle属性を設定する。
以下がサンプルコード。ついでにテキストカラーも設定している。

UILabel

let label = UILabel()
let text = "..."

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 8
let attributes: [NSAttributedString.Key: Any] = [
    .paragraphStyle: paragraphStyle,
    .foregroundColor: appPrimary
]
label.attributedText = NSAttributedString(
    string: text, attributes: attributes)

UITextView

let textView = UITextView()
let text = "..."

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 8
let attributes: [NSAttributedString.Key: Any] = [
    .paragraphStyle: paragraphStyle,
    .foregroundColor: appPrimary
]
textView.attributedText = NSAttributedString(
    string: text, attributes: attributes)