Label under image in UIButton

后端 未结 30 1979
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 15:53

I\'m trying to create a button which has some text beneath the icon (sorta like the app buttons) however it seems to be quite difficult to achieve. Any ideas how can I go ab

30条回答
  •  时光取名叫无心
    2020-11-29 16:27

    Use this two methods:

    func titleRect(forContentRect contentRect: CGRect) -> CGRect
    func imageRect(forContentRect contentRect: CGRect) -> CGRect
    

    Example:

    class VerticalButton: UIButton {
    
      override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
        let titleRect = super.titleRect(forContentRect: contentRect)
        let imageRect = super.imageRect(forContentRect: contentRect)
    
        return CGRect(x: 0,
                      y: contentRect.height - (contentRect.height - padding - imageRect.size.height - titleRect.size.height) / 2 - titleRect.size.height,
                      width: contentRect.width,
                      height: titleRect.height)
      }
    
      override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
        let imageRect = super.imageRect(forContentRect: contentRect)
        let titleRect = self.titleRect(forContentRect: contentRect)
    
        return CGRect(x: contentRect.width/2.0 - imageRect.width/2.0,
                      y: (contentRect.height - padding - imageRect.size.height - titleRect.size.height) / 2,
                      width: imageRect.width,
                      height: imageRect.height)
      }
    
      private let padding: CGFloat
      init(padding: CGFloat) {
        self.padding = padding
    
        super.init(frame: .zero)
        self.titleLabel?.textAlignment = .center
      }
    
      required init?(coder aDecoder: NSCoder) { fatalError() }
    }
    
    extension UIButton {
    
      static func vertical(padding: CGFloat) -> UIButton {
        return VerticalButton(padding: padding)
      }
    }
    

    And you can use:

    let myButton = UIButton.vertical(padding: 6)
    

提交回复
热议问题