storyboard positioning text below image inside a button

前端 未结 8 1110
野趣味
野趣味 2021-02-01 13:13

I am able to set the image and text for button. But it is aligned horizontally. I want the image and text to be aligned vertically inside the button. i.e., text below the image<

8条回答
  •  野的像风
    2021-02-01 13:35

    I've written an extension that do the works for you, Swift 4 compatible.

    public extension UIButton {
    
        func alignTextBelow(spacing: CGFloat = 6.0) {
            if let image = self.imageView?.image {
                let imageSize: CGSize = image.size
                self.titleEdgeInsets = UIEdgeInsetsMake(spacing, -imageSize.width, -(imageSize.height), 0.0)
                let labelString = NSString(string: self.titleLabel!.text!)
                let titleSize = labelString.size(withAttributes: [NSAttributedStringKey.font: self.titleLabel!.font])
                self.imageEdgeInsets = UIEdgeInsetsMake(-(titleSize.height + spacing), 0.0, 0.0, -titleSize.width)
            }
        }
    
    }
    

    Where spacing is the distance between image and text.

提交回复
热议问题