2011-06-23 58 views
0

我有下面的代碼將rightbarbuttonitemrightbarbuttonitem不顯示

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

但它不顯示任何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]; 

回答

1

您是否試圖爲rightbutton設置適當的框架?例如rightbutton.frame = (CGRect){CGPointZero, image.size};

還要注意:

在iOS 4及更高版本,不需要 文件名來指定 文件擴展名。在iOS 4之前, 必須指定文件名 擴展名。

+0

你能給示例代碼,請即如何做到這一點? –

+0

我的答案包含示例代碼。你需要做的是聲明一個image變量並將其設置爲你的圖像。 – cxa

+0

感謝它的工作 –

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]; 
2

不要忘記,如果你使用的是白色的導航欄設置tintColor上的UIBarButtonItem。我的按鈕在那裏,但看不見。

0

使用SWIFT 3.0的iOS 10.0

讓的CustomButton =的UIBarButtonItem(標題: 「右」,風格:.plain,目標:自我,動作:#selector(耶)) customButton.width = 100.0 navigationItem。 rightBarButtonItem =的CustomButton

FUNC耶(發件人:的UIBarButtonItem){ 打印( 「喲你的男人/女人」) }

相關問題