将自定义button添加到UINavigationItem LeftBarButtonItem

谁能告诉我为什么这个代码不工作?

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上没有显示。 那就是问题所在。

从文档:

“当创build一个自定义button – 这是一个types为UIButtonTypeCustom的button时,button的框架最初设置为(0,0,0,0)。在将button添加到界面之前,您应该将框架更新为更合适的价值“。

所以你应该看到的东西,如果你设置在第2行的框架,例如:

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

这应该工作

 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;