Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i offset UIButton image inside UIBarButtonItem on navBar?

Here is the code i am using to insert a custom UIBarButtonItem as the leftButton on my navbar. The issue is that the button is too close to the left edge and i cant figure out how to indent it a little without using another image with padding on the left?

UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
btn.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
[btn setBackgroundImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
self.myBtn = btn;
[btn release];

UIBarButtonItem *barBtn = [[UIBarButtonItem alloc] initWithCustomView:self.myBtn];
self.myBarBtn = barBtn;
self.myBarBtn.imageInsets = UIEdgeInsetsMake(0, 5, 0, 0);
[self.navigationItem setLeftBarButtonItem:self.myBarBtn animated:YES];
[barBtn release];

I've tried adjusting the frame, edgeInsets, all without any luck. The barButtonItem is still too close to the left edge. Is there any way to offset the image for the button?

Thx

like image 707
James Avatar asked Aug 21 '11 19:08

James


1 Answers

    UIImage *buttonImage = [UIImage imageNamed:@"Close.png"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:buttonImage forState:UIControlStateNormal];
    button.imageEdgeInsets = UIEdgeInsetsMake(0, -40, 0, 0);
    button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);

    [button addTarget:self action:@selector(donePressed:) forControlEvents:UIControlEventTouchUpInside];

    //create a UIBarButtonItem with the button as a custom view
    UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = customBarItem;
like image 138
hariszaman Avatar answered Nov 15 '22 08:11

hariszaman