2
votes

I have been trying to align an image on the left of a button while also placing some text in the center of a button. I have been following this stack overflow post: Left-align image and center text on UIButton.

I followed one of the answers that worked the best for me. Here is the code for that answer:

@IBDesignable class LeftAlignedButton: UIButton {
    override func layoutSubviews() {
        super.layoutSubviews()

        if let image = imageView?.image {

            let margin = 30 - image.size.width / 2
            let titleRec = titleRect(forContentRect: bounds)
            let titleOffset = (bounds.width - titleRec.width - image.size.width - margin) / 2


            contentHorizontalAlignment = UIControlContentHorizontalAlignment.left
            imageEdgeInsets = UIEdgeInsetsMake(0, margin, 0, 0)
            titleEdgeInsets = UIEdgeInsetsMake(0, titleOffset, 0, 0)
        }

    }
} 

Even though this gets me really close to my desired result it does not fully accomplish what I am looking for.

Here is what my current buttons look like:

Image for how Buttons currently look

As you can probably see the text in the google button, even though centered for that particular button does not correspond with how the facebook button's text is centered. Also, the images are a bit too big, but I don't know how to make them smaller.

Here is the result I am looking for:

Image for How I want my Buttons to look

To conclude, the questions I have are how do I properly center the google button's text so it corresponds with the design of the facebook button and how do I make the images smaller.

2

2 Answers

2
votes

You can also try this one. Works well with different image widths and with different titles.

extension UIButton {
    func moveImageLeftTextCenter(imagePadding: CGFloat = 30.0){
        guard let imageViewWidth = self.imageView?.frame.width else{return}
        guard let titleLabelWidth = self.titleLabel?.intrinsicContentSize.width else{return}
        self.contentHorizontalAlignment = .left
        imageEdgeInsets = UIEdgeInsets(top: 0.0, left: imagePadding - imageViewWidth / 2, bottom: 0.0, right: 0.0)
        titleEdgeInsets = UIEdgeInsets(top: 0.0, left: (bounds.width - titleLabelWidth) / 2 - imageViewWidth, bottom: 0.0, right: 0.0)
    }
}

Usage: myButton.moveImageLeftTextCenter()

0
votes

@Rohan The issue is let margin = 30 - image.size.width / 2. You are using image width to find out the margin.The Images (facebook and google) size are different(I am assuming). So according to your code, label left margin must change with image width. So if you want to achieve You have to keep both image size similar according to your code.