右栏按钮没有显示

Aya*_*avi 0 iphone ios4 ios

我有以下代码用于放置rightbarbuttonitem

UIButton* rightbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightbutton setBackgroundImage:[UIImage imageNamed:@"share-icon.png"] forState:UIControlStateNormal];
    [rightbutton addTarget:self action:@selector(share:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:rightbutton] autorelease];
Run Code Online (Sandbox Code Playgroud)

但它没有显示任何barbuttonitem.相反,如果我使用以下代码然后出现barbutton项目,但问题是我无法在barbuttonitem上使用此代码设置触摸事件.

UIImageView *iconView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dashboard-icon.png"]];
    UIBarButtonItem *icon = [[UIBarButtonItem alloc] initWithCustomView:iconView];
    self.navigationItem.leftBarButtonItem=icon;
    [icon release];
    [iconView release];
Run Code Online (Sandbox Code Playgroud)

Flo*_*ori 7

我的猜测是,你添加UIBarButtonItem到错误的对象!你需要将它添加到rootViewController(而不是UINavigationController像你所做的那样)

YourRootViewController *theRootController = [[YourRootViewController alloc] init];

UINavigationController* navContainer = [[UINavigationController alloc] initWithRootViewController:theRootController];

UIButton* rightbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightbutton setBackgroundImage:[UIImage imageNamed:@"share-icon.png"] forState:UIControlStateNormal];
    [rightbutton addTarget:self action:@selector(share:) forControlEvents:UIControlEventTouchUpInside];
 theRootController.navigationItem.rightBarButtonItem = rightbutton;

[navContainer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[self presentModalViewController:navContainer animated:YES];
Run Code Online (Sandbox Code Playgroud)