3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UIButtonでタイトルを改行する方法 in Swift3.0

Posted at

開発環境

Xcode8.1
Swift3.0 + Autolayout
iOS9+

Autolayoutでハマった

UIButtonのタイトルなんて、簡単に改行できるだろうと思っていました。
ところが、どっこいかなり苦戦し半日程浪費してしまいました。

実現方法

(1)以下のUIButtonのサブクラスを作成

MultiLineButton.swift
import UIKit

class MultiLineButton: UIButton {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        self.commonInit()
    }
    
    private func commonInit() {
        self.titleLabel?.numberOfLines = 0
        self.titleLabel?.lineBreakMode = .byWordWrapping
    }

    
    override public var intrinsicContentSize: CGSize {
        //...
        return titleLabel?.intrinsicContentSize ?? CGSize.zero
    }
    

    override func layoutSubviews() {
        super.layoutSubviews()
        titleLabel?.preferredMaxLayoutWidth = titleLabel?.frame.size.width ?? 0
        super.layoutSubviews()
    }

}

(2)UIButtonのTypeをCustomに変更
(3)Storyboardで改行したいUIButtonのクラスをMultiLineButtonに変更

以上で、完成です。
もしこちらより、良い方法や別の方法があればご連絡ください。

引用

Multiline UIButton and autolayout
http://stackoverflow.com/questions/23845982/multiline-uibutton-and-autolayout

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?