【Xcode】UIButtonのタイトルを改行させる方法
UIButtonのタイトルを改行したい
UIButtonのタイトルが長くて、↓こんな風に省略されてしまいました。
https://gyazo.com/e4b0196ae612b0af93839624804ed807
そこで、タイトルを改行する方法を調べてみたら、こちらの記事iOS7.1でボタンのタイトルが改行しなくなったら見るメモにたどりつきました。
タイトルを改行してみよう
基本的には上の記事で紹介されている通りです。
UIButtonの titleLabel には numberOfLines プロパティがあるので、こちらに 0 を設定します。
code: Swift
@IBOutlet weak var titleButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
titleButton.titleLabel?.numberOfLines = 0
titleButton.setTitle("タイトルの文字列です。すごく長いので改行して欲しいのですよ。", for: .normal)
}
すると、こちら↓のように自動的に改行してくれます。
https://gyazo.com/5d7be64bc0c3657e4aa6506e4f0e06d7
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のアニメーションをオフにします。
code: Swift
@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)
}
【Xcode】UIButtonのタイトルを改行させる方法