Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an image inside UIButton as an accesory

I have the following UIButton I want to add an Image inside to the far right. Like an accessoryView

I am already using backgroundImage and I want to avoid combining the 2 images into 1.

Is it possible to add another image inside the UIButton that is an AccesoryView lets say an image that has a PLUS to the far right? ( I am looking to a way to insert the new image inside the Button)

enter image description here

@luisCien comment

I tried

    [_addImage setImage:[UIImage imageNamed:@"shareMe"] forState:UIControlStateNormal];
   _addImage.contentHorizontalAlignment =
        UIControlContentHorizontalAlignmentRight;

and it looks like this, I would like to image to be on the right side of the text. enter image description here

like image 588
Jonathan Thurft Avatar asked Jun 11 '13 21:06

Jonathan Thurft


2 Answers

Just add it as a subview and choose your coordinates..Try something like this:

UIImageView *yourPlusSign = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"yourPlusSignImageTitle"]];
yourPlusSign.frame = CGRectMake(x, y, width, height);//choose values that fit properly inside the frame of your baseButton
//or grab the width and height of yourBaseButton and change accordingly
yourPlusSign.contentMode=UIViewContentModeScaleAspectFill;//or whichever mode works best for you
[yourBaseButton addSubview:yourPlusSign];
like image 61
Tommy Devoy Avatar answered Oct 07 '22 19:10

Tommy Devoy


You can use the contentHorizontalAlignment property of UIButton and set it to UIControlContentHorizontalAlignmentRight this will position the image you add to it to the far right.

Edit: As suggested by @danypata you can also use UIButton's property imageEdgeInsets to leave some margin around your 'accessoryView' like so:

[_addImage setImageEdgeInsets:UIEdgeInsetsMake(5, 0, 5, 10)];

Regarding having the text on the left and the image on the right, I believe it's not possible (someone please correct me). For that I would either create my own custom button by extending UIControl or add a UILabel and set it's frame (as opposed to using UIButton's setTitle:forState:) and add it as a subview of the button.

Hope this helps!

like image 2
LuisCien Avatar answered Oct 07 '22 19:10

LuisCien