複数行テキストのボタンをAutoLayoutで配置したら、テキスト量によって改行するボタンを作りたかったんだけど、ハマってしまって改行してくれないボタンになってしまった。
作りとしては、UITableViewに改行ボタンを配置したカスタムセルを表示しているだけです。
AutoLayoutで複数行テキストのボタンが正しく改行されないのを修正した
きちんと改行してくれるように修正しました。
CustomButton.swift
CustomButton#intrinsicContentSize
を適切なサイズで返すと綺麗に改行させて表示させることができました。
import UIKit class CustomButton: UIButton { override func awakeFromNib() { super.awakeFromNib() titleLabel?.numberOfLines = 0 titleLabel?.lineBreakMode = .byCharWrapping titleLabel?.textAlignment = .left titleEdgeInsets = UIEdgeInsets(top: 0, left: 24, bottom: 0, right: 20) } override var intrinsicContentSize: CGSize { let margin = self.titleEdgeInsets.left + self.titleEdgeInsets.right var size = CGSize(width: self.frame.width - margin, height: CGFloat.greatestFiniteMagnitude) size = self.titleLabel?.sizeThatFits(size) ?? CGSize.zero size = CGSize(width: size.width, height: size.height + 16) return size } override func layoutSubviews() { super.layoutSubviews() titleLabel?.preferredMaxLayoutWidth = titleLabel!.frame.width super.layoutSubviews() } }
CustomTableViewCell.swift
import UIKit class CustomTableViewCell: UITableViewCell { @IBOutlet weak var button: UIButton! @IBOutlet weak var heightLayoutConstraint: NSLayoutConstraint! var title: String? { didSet { updateDisplay() } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } fileprivate func updateDisplay() { guard let title = title else { return } button.setTitle(title, for: .normal) button.setTitleColor(.black, for: .normal) } }
MasterViewController.swift
var objects = [String]() override func viewDidLoad() { super.viewDidLoad() objects = [ //省略 ] tableView.register(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "customCell") tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 300 } // MARK: - Table View override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomTableViewCell cell.title = objects[indexPath.row] return cell }
関連記事
この他にもiOSアプリ開発で見つけたネタや悩んだ内容など紹介しています。Tipsをまとめておりますのでこちらのページをご参照ください。