user6631314
user6631314

Reputation: 1960

Possible to left align button text but right align background or button image?

Hi I have a UIButton created in Storyboard where I would like to left align the title but right align the image. So far, I've been unable to find a way to do it. I know it is possible to add a separate UIImage but for purposes of simplifying autolayout I was hoping to do it all with one button.

Is such a thing possible either in storyboard or with code? Thanks in advance for any suggestions

Upvotes: 0

Views: 68

Answers (3)

AechoLiu
AechoLiu

Reputation: 18368

My UIButton extension methods, in Swift. Sorry about it's not obj-c. My projects are almost written by Swift now.

extension UIButton {
    // ## Usage
    // let btn: UIButton = //... UIButton
    //
    // ... configure `image` and `text` before calling following method. 
    // btn.myImageRightAligned()
    // Let image of `UIButton` aligned right. 

    public func myImageRightAligned(_ spacing: CGFloat = 2.0) {
        let button = self
        guard (button.imageView != nil && button.imageView?.image != nil) else {
            return
        }
        guard (button.titleLabel != nil && button.titleLabel?.text != nil) else {
            return
        }
        let imageSize = button.imageView!.image!.size
        let title = button.titleLabel!.text! as NSString
        let titleSize = title.size(attributes: [NSFontAttributeName: button.titleLabel!.font])

        button.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -(imageSize.width + spacing), bottom: 0.0, right: imageSize.width)
        button.imageEdgeInsets = UIEdgeInsets(top: 0.0, left:  titleSize.width, bottom: 0.0, right: -(titleSize.width + spacing))

        self.setNeedsLayout()
    }
}

Upvotes: 1

nathanwhy
nathanwhy

Reputation: 6134

overwrite this in subclass:

- (CGRect)titleRectForContentRect:(CGRect)contentRect;
- (CGRect)imageRectForContentRect:(CGRect)contentRect;

then use this subclass in storyboard

Upvotes: 1

Mostafa Sultan
Mostafa Sultan

Reputation: 2438

You can change button image offset (changing position) from element inspector in storyboard, i don't get the meaning of aligning the background as it covers the whole button there is no left and right in this

Upvotes: 0

Related Questions