LoginSignup
24
11

More than 1 year has passed since last update.

【Xcode】UIButtonのタイトルを改行させる方法

Last updated at Posted at 2018-07-30

UIButtonのタイトルを改行したい

UIButtonのタイトルが長くて、↓こんな風に省略されてしまいました。

001.png

そこで、タイトルを改行する方法を調べてみたら、こちらの記事iOS7.1でボタンのタイトルが改行しなくなったら見るメモにたどりつきました。

タイトルを改行してみよう

基本的には上の記事で紹介されている通りです。
UIButtonの titleLabel には numberOfLines プロパティがあるので、こちらに 0 を設定します。

    @IBOutlet weak var titleButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        titleButton.titleLabel?.numberOfLines = 0
        titleButton.setTitle("タイトルの文字列です。すごく長いので改行して欲しいのですよ。", for: .normal)
    }

すると、こちら↓のように自動的に改行してくれます。

002.png

numberOfLinesとは

numberOfLinesは、UILabelのプロパティです。

アップルの公式ドキュメントnumberOfLines - UILabel | Apple Developer Documentationでは、↓こちらのように解説されています。

This property controls the maximum number of lines to use in order to fit the label’s text into its bounding rectangle. The default value for this property is 1. To remove any maximum limit, and use as many lines as needed, set the value of this property to 0.
(Google翻訳)このプロパティは、境界矩形にラベルを収めるために使用する行の最大数を制御します。 最大限度を削除し、必要な数だけ行を使用するには、このプロパティの値を0に設定します。

初期値は1が設定されていて1行で表示されます。
2行にしたいときは2を設定します。
テキストに合わせて無制限に改行するときは、0を設定します。

ボタンのタイトルがふわっとアニメーションしないようにする方法

UIButtonに setTitle:forState: でタイトルを設定すると、タイトル文字を表示するときに、自動的にふわっとアニメーションします。

このアニメーションをオフにしたいときは、以下のように一時的にUIViewのアニメーションをオフにします。

    @IBOutlet weak var titleButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        UIView.setAnimationsEnabled(false)
        titleButton.titleLabel?.numberOfLines = 0
        titleButton.setTitle("タイトルの文字列です。すごく長いので改行して欲しいのですよ。", for: .normal)
        titleButton.layoutIfNeeded()
        UIView.setAnimationsEnabled(true)
    }
24
11
1

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
24
11