LoginSignup
3
4

More than 3 years have passed since last update.

UIButtonのtitlelabelのテキストを全て表示する方法[Swift]

Last updated at Posted at 2019-12-20

動機

UIButtonのテキストを設定していて幅の制約は横いっぱいに広げていて
余白はめちゃめちゃあるはずなのにテキストが見切れるのに苦戦したのでメモ。

概要

  • これだと見切れる ->titleLabelのテキスト(つまり中身)を指定しただけなので、大きさはxcodeで指定した文字列によって決まってしまう (Xcode側で適当に長い文字列をあらかじめ入れておいてもうまくいくのがこのため)
hugaButton.titleLabel?.text = "hogehoge"
  • これも見切れる ->adjustsFontSizeToFitWidthtitleLabelの大きさに合わせて 全ての文字が入るようフォントを調節するのでtitleLabel大きさを調節してくれるわけではない
hugaButton.titleLabel?.text = "hogehoge"
hugaButton.titleLabel?.adjustsFontSizeToFitWidth = true
  • これだとOK ->setTitleはテキストに合わせてtitleLabelの大きさを調節し、テキストを入れてくれるので全てのテキストが表示される(フォントはデフォはXcode側の設定に準拠するので変更したい場合は別途コードで設定が必要)
hugaButton.setTitle("hogehoge", for: UIControl.State.normal)

備考

フォント変更はこうやるらしい
setTitletitleLabelに文字が入るのが納得って感じです

let updateBtn: UIButton = UIButton()
//ボタンタイトル //titleLabelに更新を入れる
updateBtn.setTitle("更新", forState: UIControlState.Normal)
//ボタンタイトルのフォントサイズ
updateBtn.titleLabel?.font = UIFont.systemFontOfSize(25)

参考

http://daifuku-p.org/w/?p=767
http://mob-wasao.hatenablog.jp/entry/2017/03/10/152149

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