5

titleEdgeInsets used to align the title and the picture on the button. I did image on the left and title on the right.But when I click on the button, the title is shifting to the left. Thank you

UIImage *image = [UIImage imageNamed:imageName];
    [self setImage:image forState:UIControlStateNormal];

CGSize imageSize = self.imageView.frame.size;
CGSize titleSize = self.titleLabel.frame.size;

self.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
self.titleEdgeInsets = UIEdgeInsetsMake(0, ((self.frame.size.width-titleSize.width)/2)-imageSize.width, 0, 0);
self.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

status is normal

status is clicked

hiwordls
  • 781
  • 7
  • 17
  • 35
  • Could it be because you set the image only for `UIControlStateNormal´ – chris13 Aug 28 '13 at 10:15
  • I have found behavior of edge insets very counterintuitive so I created a little demo app that you can play with https://github.com/tomas789/UIButtonEdgeInsets – tomas789 Jan 23 '17 at 09:05

1 Answers1

16

This is the example another way for setting the title and image in straight ----> :) try this way,

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
aButton.frame = CGRectMake(0, 0, self.view.bounds.size.width, 40);
[aButton setImage:[UIImage imageNamed:@"imageName"] forState:UIControlStateNormal];
[aButton setTitle:@"Rate us on app store" forState:UIControlStateNormal];
[aButton setTitleEdgeInsets:UIEdgeInsetsMake(2, 50, 2, 20)];//set ur title insects also
[aButton setImageEdgeInsets:UIEdgeInsetsMake(2, -200, 2, 2)];//make negative edge for left side
[aButton setBackgroundColor:[UIColor greenColor]];
[self.view addSubview:aButton];


Shankar BS
  • 8,394
  • 6
  • 41
  • 53