Multiline UIButton and autolayout

后端 未结 16 1495
无人共我
无人共我 2020-12-03 13:08

I have created a view controller that looks like this:

\"enter

I want the two

16条回答
  •  情歌与酒
    2020-12-03 13:49

    Version, which also taking into account titleEdgeInsets and not overrides standard button behaviour unless titleLabel?.numberOfLines set to zero and button image set to nil.

    open class Button: UIButton {
    
       override open var intrinsicContentSize: CGSize {
          if let titleLabel = titleLabel, titleLabel.numberOfLines == 0, image == nil {
             let size = titleLabel.intrinsicContentSize
             let result = CGSize(width: size.width + contentEdgeInsets.horizontal + titleEdgeInsets.horizontal,
                                 height: size.height + contentEdgeInsets.vertical + titleEdgeInsets.vertical)
             return result
          } else {
             return super.intrinsicContentSize
          }
       }
    
       override open func layoutSubviews() {
          super.layoutSubviews()
          if let titleLabel = titleLabel, titleLabel.numberOfLines == 0, image == nil {
             let priority = UILayoutPriority.defaultLow + 1
             if titleLabel.horizontalContentHuggingPriority != priority {
                titleLabel.horizontalContentHuggingPriority = priority
             }
             if titleLabel.verticalContentHuggingPriority != priority {
                titleLabel.verticalContentHuggingPriority = priority
             }
             let rect = titleRect(forContentRect: contentRect(forBounds: bounds))
             titleLabel.preferredMaxLayoutWidth = rect.size.width
             super.layoutSubviews()
          }
       }
    }
    

提交回复
热议问题