Label under image in UIButton

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

    Here is "Bear With Me"s answer as a subclass in Swift 2.0. To use it just change your button class in Interface Builder to VerticalButton and it will magically update the preview.

    I also updated it to calculate the correct intrinsic content size for autolayout.

    import UIKit
    
    @IBDesignable
    
    class VerticalButton: UIButton {
        @IBInspectable var padding: CGFloat = 8
    
        override func prepareForInterfaceBuilder() {
            super.prepareForInterfaceBuilder()
    
            update()
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
    
            update()
        }
    
        func update() {
            let imageBounds = self.imageView!.bounds
            let titleBounds = self.titleLabel!.bounds
            let totalHeight = CGRectGetHeight(imageBounds) + padding + CGRectGetHeight(titleBounds)
    
            self.imageEdgeInsets = UIEdgeInsets(
                top: -(totalHeight - CGRectGetHeight(imageBounds)),
                left: 0,
                bottom: 0,
                right: -CGRectGetWidth(titleBounds)
            )
    
            self.titleEdgeInsets = UIEdgeInsets(
                top: 0,
                left: -CGRectGetWidth(imageBounds),
                bottom: -(totalHeight - CGRectGetHeight(titleBounds)),
                right: 0
            )
        }
    
        override func intrinsicContentSize() -> CGSize {
            let imageBounds = self.imageView!.bounds
            let titleBounds = self.titleLabel!.bounds
    
            let width = CGRectGetWidth(imageBounds) > CGRectGetWidth(titleBounds) ? CGRectGetWidth(imageBounds) : CGRectGetWidth(titleBounds)
            let height = CGRectGetHeight(imageBounds) + padding + CGRectGetHeight(titleBounds)
    
            return CGSizeMake(width, height)
        }
    }
    

提交回复
热议问题