Venc
Venc

Reputation: 115

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

Upvotes: 3

Views: 3094

Answers (1)

Julian Silvestri
Julian Silvestri

Reputation: 2027

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()
}

Upvotes: 7

Related Questions