7

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

James
  • 93
  • 1
  • 4

2 Answers2

4
    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;
hariszaman
  • 8,202
  • 2
  • 40
  • 59
-1

there is the custom left or right button with swift language

let buttonEdit: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
buttonEdit.frame = CGRectMake(0, 0, 40, 40)
buttonEdit.setImage(UIImage(named:"nav-right-Y.png"), forState: UIControlState.Normal)
buttonEdit.addTarget(self, action: "rightNavItemEditClick", forControlEvents: UIControlEvents.TouchUpInside)
var rightBarButtonItemEdit: UIBarButtonItem = UIBarButtonItem(customView: buttonEdit)
self.navigationItem.rightBarButtonItem = rightBarButtonItemEdit
Dani Pralea
  • 4,545
  • 2
  • 31
  • 49
fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88