Monday, July 16, 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 grayColorforState:UIControlStateNormal];
  [button setTitleColor:[UIColor whiteColorforState: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)-1500)];




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.

No comments:

Post a Comment