Label under image in UIButton

后端 未结 30 1990
佛祖请我去吃肉
佛祖请我去吃肉 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:19

    corrected one of the answers here:

    Swift 3:

    class CenteredButton: UIButton
    {
        override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
            let rect = super.titleRect(forContentRect: contentRect)
            let imageRect = super.imageRect(forContentRect: contentRect)
    
            return CGRect(x: 0, y: imageRect.maxY + 10,
                          width: contentRect.width, height: rect.height)
        }
    
        override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
            let rect = super.imageRect(forContentRect: contentRect)
            let titleRect = self.titleRect(forContentRect: contentRect)
    
            return CGRect(x: contentRect.width/2.0 - rect.width/2.0,
                          y: (contentRect.height - titleRect.height)/2.0 - rect.height/2.0,
                          width: rect.width, height: rect.height)
        }
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            centerTitleLabel()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            centerTitleLabel()
        }
    
        private func centerTitleLabel() {
            self.titleLabel?.textAlignment = .center
        }
    }
    

提交回复
热议问题