UIButton: How to set image and text using imageEdgeInsets and titleEdgeInsets?

hacker picture hacker · Jun 20, 2013 · Viewed 8.5k times · Source

I had an application in which I am using a UIButton with a title and UIImage. Their alignment seems to be first title then after that the UIImage.

I had tried this:

[dropdownbutton setImage: [UIImage imageNamed:@"down_sml_arrow.png"] 
                                     forState:UIControlStateNormal];
CGFloat spacing = 10; // the amount of spacing to appear between image and title
dropdownbutton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, spacing);
dropdownbutton.titleEdgeInsets = UIEdgeInsetsMake(0, spacing, 0, 0);
[dropdownbutton setTitle:@"Your text" forState:UIControlStateNormal];

but here the UIImage is coming before the title. Can anybody point me in where I am going wrong?

Answer

Vivek Sehrawat picture Vivek Sehrawat · Jun 20, 2013

Alternate

UIImageView *imageView1=[[UIImageView alloc]init];
UIButton *dropdownbutton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
dropdownbutton.frame=CGRectMake(50, 50, 120, 50);
imageView1.image=[UIImage imageNamed:@"arrows.png"];
imageView1.frame=CGRectMake(85, 12, 25, 25);
dropdownbutton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[dropdownbutton addSubview:imageView1];
CGFloat spacing = 10; // the amount of spacing to appear between image and title
dropdownbutton.titleEdgeInsets = UIEdgeInsetsMake(0, spacing, 0, 0);
[dropdownbutton setTitle:@"Your text" forState:UIControlStateNormal];
[self.view addSubview:dropdownbutton];