将自定义按钮添加到UINavigationItem LeftBarButtonItem

问题描述:

谁能告诉我为什么此代码不起作用?

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;

leftBarButtonItem上没有任何内容.那是问题.

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

来自文档:

创建自定义按钮(即UIButtonTypeCustom类型的按钮时,按钮的框架最初设置为(0,0,0,0).在将按钮添加到界面之前,应更新设置为更合适的值."

"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."

因此,如果在第2行中设置框架,您应该会看到一些东西,例如:

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

self.backButton.frame = CGRectMake(0, 0, 40, 20);