Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton image on top of the text

I have two dynamic size button and i need make image and title text for them. Image must be on top and text under image and both must is in the center of the button. I try do it with imageEdgeInsatse but can't understand what I am do wrong.

Here is my code:

leftButton.imageEdgeInsets = UIEdgeInsets(top: 5, left:0, bottom: 60, right: 0)
leftButton.titleEdgeInsets = UIEdgeInsets(top: 60, left: 0, bottom: 5, right: 0)

rightButton.imageEdgeInsets = UIEdgeInsets(top: 5, left: 0, bottom: 60, right: 0)
rightButton.titleEdgeInsets = UIEdgeInsets(top: 60, left: 0, bottom: 5, right: 0)

enter image description here

like image 718
Venc Avatar asked Nov 05 '25 06:11

Venc


1 Answers

Try using this code extension.

extension UIButton {
    func alignVertical(spacing: CGFloat = 6.0) {
        guard let imageSize = self.imageView?.image?.size,
            let text = self.titleLabel?.text,
            let font = self.titleLabel?.font
            else { return }
        self.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -imageSize.width, bottom: -(imageSize.height + spacing), right: 0.0)
        let labelString = NSString(string: text)
        let titleSize = labelString.size(withAttributes: [kCTFontAttributeName as NSAttributedStringKey: font])
        self.imageEdgeInsets = UIEdgeInsets(top: -(titleSize.height + spacing), left: 0.0, bottom: 0.0, right: -titleSize.width)
        let edgeOffset = abs(titleSize.height - imageSize.height) / 2.0;
        self.contentEdgeInsets = UIEdgeInsets(top: edgeOffset, left: 0.0, bottom: edgeOffset, right: 0.0)
    }
}

use the extension like this

override func viewDidLayoutSubviews() {
    button.alignVertical()
}
like image 111
Julian Silvestri Avatar answered Nov 07 '25 05:11

Julian Silvestri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!