開発環境
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