Jonathan
Jonathan

Reputation: 742

UIButton with right image and centered text

I need to create a UIButton with an image on right and a text in center. Like this :

enter image description here

Thanks to answer of "ios Developer", I've written a code that make what I want by adding the image and text on button and change edge insets :

+ (void)addImageWithName:(NSString *)imageName onButton:(UIButton *)btn {
    [btn setImage:image forState:UIControlStateNormal];
    [btn setImage:image forState:UIControlStateHighlighted];

    CGFloat margin = 10.f;
    btn.imageEdgeInsets = UIEdgeInsetsMake(0.f, btn.frame.size.width - image.size.width - margin, 0.f, 0.f);

    btn.titleEdgeInsets = UIEdgeInsetsMake(0.f, -image.size.width - margin, 0.f, 0.f);
}

Text is added with this code :

[btn setTitle:@"hello world" forState:UIControlStateNormal];

But if text is too long, it goes above image and goes outside button. How can I prevend this ?

enter image description here

Upvotes: 0

Views: 396

Answers (1)

Anirban iOS
Anirban iOS

Reputation: 977

if you are working on Xcode 8.2.1 then you can find Button Content Insets, Title Insets & Image Insets in Size Inspector section in Story Board ViewController.If you are working in xcode 7 or lower the you can find that option in Attribute Inspector section.You can set Title insets & Image Insets as per requirement.

Upvotes: 1

Related Questions