1

Could anyone tell me why this code does not working?

self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.backButton setImage:[UIImage imageNamed:@"back_arrow.png"]
                 forState:UIControlStateNormal];
self.backButton.contentMode = UIViewContentModeCenter;
[self.backButton addTarget:self
                    action:@selector(backButtonAction:)
          forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.backButton];
[navigationItem setLeftBarButtonItem:backButtonItem animated:NO];
navigationItem.hidesBackButton = YES;

Edit:

Nothing appears on the leftBarButtonItem. That's the problem.

Lorenzo B
  • 33,216
  • 24
  • 116
  • 190
Abdalrahman Shatou
  • 4,550
  • 6
  • 50
  • 79

2 Answers2

2

This should work

CGRect rect = CGRectMake(10, 0, 30, 30);
self.backButton = [[UIButton alloc] initWithFrame:rect];
[self.backButton setImage:[UIImage imageNamed:@"back_arrow.png"]
                 forState:UIControlStateNormal];
self.backButton.contentMode = UIViewContentModeCenter;
[self.backButton addTarget:self
                    action:@selector(backButtonAction:)
          forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.backButton];
self.navigationItem.leftBarButtonItem = backButtonItem;
self.navigationItem.hidesBackButton = YES;
humblemenon
  • 86
  • 1
  • 6
2

From the docs:

"When creating a custom button—that is a button with the type UIButtonTypeCustom—the frame of the button is set to (0, 0, 0, 0) initially. Before adding the button to your interface, you should update the frame to a more appropriate value."

So you should see something if you set the frame in line 2, eg:

self.backButton.frame = CGRectMake(0, 0, 40, 20);
foundry
  • 31,615
  • 9
  • 90
  • 125