LoginSignup
33
14

More than 5 years have passed since last update.

【Swift4.2】UILabelに行間を設定する

Last updated at Posted at 2019-03-03

概要

iOSアプリ開発のUIでよく使われる UILabel に行間を設定する2つの方法を紹介します

前提

  • Xcode 10.1
  • Swift 4.2

Storyboardで設定する

まずは適当な Storyboard or xib 開き、UILabelを設置します。

スクリーンショット 2019-03-02 11.22.59.png

画面右側の InspectorAttribute Inspector を見てみます

スクリーンショット 2019-03-02 11.23.08.png

Label -> TextPlain の状態では行間を設定できないので、ここをattributedに変更します

最後に、下記GIFのように設定すると行間を変更できます

line-height-storyboard.gif

Simulator Screen Shot - iPhone 8 - 2019-03-02 at 11.15.46.png

コードから動的に変更する

  • IBOutlet接続する
  • UILabelのattributedText に NSAttributedString をセットする
class ViewController: UIViewController {

    @IBOutlet private weak var titleLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        var attributes: [NSAttributedStringKey: Any] = [:]
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 10.0
        paragraphStyle.alignment = .center
        attributes.updateValue(paragraphStyle, forKey: .paragraphStyle)
        titleLabel.attributedText = NSAttributedString(string: "投稿がありません\n最初の投稿をしてみよう", attributes: attributes)
    }
}

他の画面でも簡単に使えるように、 NSAttributedStringextensionに定義しておきましょう

class ViewController: UIViewController {

    @IBOutlet private weak var titleLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        titleLabel.attributedText = NSAttributedString(string: "投稿がありません\n最初の投稿をしてみよう", lineSpacing: 10.0, alignment: .center)
    }
}

extension NSAttributedString {
    convenience init(string: String, lineSpacing: CGFloat, alignment: NSTextAlignment) {
        var attributes: [NSAttributedStringKey: Any] = [:]
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = lineSpacing
        paragraphStyle.alignment = alignment
        attributes.updateValue(paragraphStyle, forKey: .paragraphStyle)
        self.init(string: string, attributes: attributes)
    }
}
33
14
6

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
33
14