Thursday, March 22, 2012

How to use ImageEdgeInsets in UIButton ?

If you are unhappy with the location of image on your button, you can place the image as per your choice anywhere in your button bounding rect.

Here is a sample code to create a button, You can create it Interface Builder too.



  UIButton *button=[[UIButton alloc]initWithFrame:a];
  [button addTarget:self action:@selector(ButtonClickedOnFirstNavigationBar:) forControlEvents:UIControlEventTouchUpInside];
  button.titleLabel.font=[UIFont fontWithName:@"Helvetica" size:10];
  [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
  [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
  [button setTitle:@"Find Report" forState:UIControlStateNormal];
  [button setBackgroundColor:[UIColor clearColor]];
 [button setImage:[UIImage imageNamed:@"MyReport.png"] forState:UIControlStateNormal];
  [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
  [self.view addSubview:button];



Following is what the button looks like. Button Image by default sticks to the left margin.






I want move the image close to the right margin so I use ImageEdgeInsets. Lets add following line:



[button setImageEdgeInsets:UIEdgeInsetsMake(0, CGRectGetWidth(button.frame)-15, 0, 0)];





Now our button looks like following:


UIEdgeInsetsMake is really really simple to implement. First argument tells how much margin you want between image and top bound,
second argument is margin you want on left,
third argument is margin you want on bottom,
fourth argument is margin on right.


1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete