views:

1185

answers:

2

Hello, guys.

If I put only an image in a button and set the imageEdgeInsets more close to the top, the image stays centered and all works as expected:

[button setImage:image forState:UIControlStateNormal];
[button setImageEdgeInsets:UIEdgeInsetsMake(-15.0, 0.0, 0.0, 0.0)];

If I put only a text in a button and set titleEdgeInsets more close to the bottom, the text stays centered and all works as expected:

[button setTitle:title forState:UIControlStateNormal];
[button setTitleEdgeInsets:UIEdgeInsetsMake(0.0, 0.0, -30, 0.0)];

But, if i put the 4 lines together the text interfere with the image and both lost the center alignment.

All my images has 30 pixels width, and if i put 30 in the left parameter of UIEdgeInsetMake for setTitleEdgeInsets, the text is centered again. The problem is that the image never gets centered because appears that it is dependent of the button.titleLabel size. I already tried many calculations with button size, image size, titleLabel size and never get both perfectly centered.

Someone already have the same problem?

Thanks in advance.

+2  A: 

Founded how.

First, configure your text of titleLabel (because of styles, i.e, bold, italic, etc). Then, put your setTitleEdgeInsets considering the width of your image:

[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setTitle:title forState:UIControlStateNormal];
[button.titleLabel setFont:[UIFont boldSystemFontOfSize:10.0]];
[button setTitleEdgeInsets:UIEdgeInsetsMake(0.0, -image.size.width, -25.0, 0.0)]; // Left inset is the negative of image width.

After that, set your setTitleEdgeInsets considering the width of text bounds:

[button setImage:image forState:UIControlStateNormal];
[button setImageEdgeInsets:UIEdgeInsetsMake(-15.0, 0.0, 0.0, -button.titleLabel.bounds.size.width)]; // Right inset is the negative of text bounds width.

Now the image and the text will be centralized (in this example, the image appears above the text).

Cheers.

R31n4ld0_
A: 

Hello can any one please help me how to add an image which is of 50X50 pixels and after the image i have to write the text and text should fit the button.i am new to iphone and object c any example code is very helpfull

Thanks in advance

shiva Inturi