user1302602
user1302602

Reputation: 419

uibutton image on the left and text on the center

I am creating a button with image on the left and text on the center. It works but somehow the background color of red doesn't cover the entire button.

    self.buyButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [self.buyButton.titleLabel setBackgroundColor:[UIColor buttonRed]];
    UIImage *image = [UIImage imageNamed:@"cart.png"];
    [self.buyButton setImage:image forState:UIControlStateNormal];
    self.buyButton.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [self.buyButton setTitle:@"Buy" forState:UIControlStateNormal];
    self.buyButton.titleEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0);
    self.buyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

[1]http://s23.postimg.org/g8hxmihyv/Screen_Shot_2013_08_07_at_5_45_40_PM.png "snapshot"

If i set the entire button to red, it looks like this. [1] http://s21.postimg.org/xdwrziphv/Screen_Shot_2013_08_07_at_5_50_15_PM.png "snapshot2"

Upvotes: 2

Views: 860

Answers (1)

Mick MacCallum
Mick MacCallum

Reputation: 130222

That's because you're only settings the background color to red for the titleLabel. Try setting the background color of the button itself while using a custom button and changing the corner radius of the button's layer (#import <QuartzCore/QuartzCore.h>). ex:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundColor:[UIColor redColor]];
[button.layer setCornerRadius:5.0f];

Additionally, you may need to change the color of the titleLabel to clearColor.

Upvotes: 3

Related Questions