自定义UIBarButton在UITableView中无法正确显示

时间:2013-01-27 05:06:58

标签: uibarbuttonitem navigationbar

我的代码成功创建了导航栏上显示的自定义UIBarButtonItem。我在其他视图控制器中使用代码,它工作得很好,但在UITableViewController中,按钮显示为常规BackButtonItem。有人可以帮我吗?这是我在所有viewControllers

中的viewDidLoad方法中使用的代码
@implementation P2OListViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {

    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.hidesBackButton = YES;

    UIImage *backButtonImage = [UIImage imageNamed:@"button-back@2x.png"];
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setImage:backButtonImage forState:UIControlStateNormal];
    backButton.frame = CGRectMake(0, 0, 60, 35);

    [backButton addTarget:self
                   action:@selector(goToMenu:)
         forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *back = [[UIBarButtonItem alloc]initWithCustomView:backButton];
    self.navigationItem.backBarButtonItem = back;

- (void)viewWillAppear:(BOOL)animated {

}

- (void)goToMenu:(id)sender {
[self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

1 个答案:

答案 0 :(得分:1)

通过将hide属性设置为yes

来隐藏默认的backBarButtonItem
self.navigationItem.hidesBackButton = YES;
在viewWillAppear

- (void)viewWillAppear:(BOOL)animated 
{
self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.hidesBackButton = YES;

    UIImage *backButtonImage = [UIImage imageNamed:@"button-back@2x.png"];
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setImage:backButtonImage forState:UIControlStateNormal];
    backButton.frame = CGRectMake(0, 0, 60, 35);

    [backButton addTarget:self
                   action:@selector(goToMenu:)
         forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *back = [[UIBarButtonItem alloc]initWithCustomView:backButton];
    self.navigationItem.backBarButtonItem = back;

}

如果上述不起作用,试试这个&看看会发生什么:

if (!self.navigationItem.backBarButtonItem.hidden) {
      self.navigationItem.backBarButtonItem.hidden = YES;
   }
   else { 
      NSLog(@"back button already hidden");
   }