IOS: Adjust UIButton height depend on title text using Autolayout?

前端 未结 4 1801
囚心锁ツ
囚心锁ツ 2021-01-02 12:40

I have a UIButton and it can change the title at the runtime. Therefore, I want to increase the UIButton height depend on the title text for displa

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-02 13:21

    Ayan Sengupta solution in Swift, with support for contentEdgeInsets (thanks Claus Jørgensen):

    (You may also further customize the code to take titleEdgeInsets into account if needed)

    1. Subclass your UIButton to take the ownership of the layout process:

       /// https://stackoverflow.com/a/50575588/1033581
       class AutoLayoutButton: UIButton {
           override var intrinsicContentSize: CGSize {
               var size = titleLabel!.sizeThatFits(CGSize(width: titleLabel!.preferredMaxLayoutWidth - contentEdgeInsets.left - contentEdgeInsets.right, height: .greatestFiniteMagnitude))
               size.height += contentEdgeInsets.left + contentEdgeInsets.right
               return size
           }
           override func layoutSubviews() {
               titleLabel?.preferredMaxLayoutWidth = frame.size.width
               super.layoutSubviews()
           }
       }
      
    2. Use this class in your storyboard, and set constraints for Leading, Trailing, Top, Bottom. But don't set any Height constraint.

    An alternative without subclassing is to add a wrapper view as suggested by Bartłomiej Semańczyk answer and Timur Bernikowich comment.

提交回复
热议问题