Adding a Custom Button to a UINavigationItem LeftB

2019-06-01 06:52发布

问题:

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.

回答1:

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);


回答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;