2013-07-31 152 views
6

我想通過向rightBarButtonItem添加一個自定義按鈕來自定義導航欄。創建一個非常簡單。將操作和目標添加到自定義導航BarButtonItem?

UIImage *myImage = [UIImage imageNamed:@"menu-icon.png"]; 

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
[myButton setFrame:CGRectMake(0, 0, myImage.size.width, myImage.size.height)]; 
[myButton setBackgroundImage:myImage forState:UIControlStateNormal]; 

UIBarButtonItem *myButtonItem = [[UIBarButtonItem alloc] initWithCustomView:myButton]; 

[navItem setLeftBarButtonItem:myButtonItem animated:YES]; 

看起來不錯,除了現在我無法設置目標或操作屬性。下面的代碼什麼也不做:

myButtonItem.target = myTarget; 
myButtonItem.action = @selector(myButtonAction); 

我發現它不工作的原因是因爲我與-initWithCustomView初始化的UIBarButtonItem。蘋果文檔說:

該方法創建的條形按鈕項目不會響應用戶交互調用其目標的動作方法。相反,酒吧按鈕項目期望指定的自定義視圖來處理任何用戶交互並提供適當的響應。

我有點困惑,究竟蘋果是什麼意思。我應該創建一個自定義控件或什麼?我還沒有真正做到這一點,我不知道從哪裏開始。

有沒有人有任何建議如何做到這一點或另一種方式來設置自定義導航欄按鈕?

回答-------------------------------------------- --------------

剛把這個方法添加到UIButton的:

[myButton addTarget:myTarget action:@selector(myButtonAction) forControlEvents:UIControlEventTouchUpInside]; 

回答

6

這很簡單,你需要添加uibutton的目標而不是uibarbuttonitem。

要解釋更多你想要的uibarbuttonitem是響應觸摸內部的行動方法,因爲文檔說,你需要爲uibutton做這個,因爲你正在初始化uibarbuttonitem與自定義視圖在你的情況下uibutton。

+0

謝謝,沒有意識到它是那麼簡單。 – DJSK

4

添加動作和目標的UIButton這樣的:

[myButton addTarget:self 
      action:@selector(handleMyButtonTap) 
    forControlEvents:UIControlEventTouchUpInside];

添加動作和目標到UIBarButtonItem像這樣:

[myBarButtonItem setAction:@selector(handleBarButtonTap)]; 
[myBarButtonItem setTarget:aTarget];
+0

它沒有一起工作myButtonItem,但是當我將它添加到myButton時它工作!謝謝! – DJSK

0

有了答案由hgwhittle穆斯塔法我實現了幫助,在這裏完美的作品 是完全剪斷可以幫助別人

 //Create ImageButton 
     UIImage *shareBtnIcon = [UIImage imageNamed:@"dummy_share_icon_22"]; 

     UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
     [shareButton setFrame:CGRectMake(0, 0, shareBtnIcon.size.width, shareBtnIcon.size.height)]; 
     [shareButton setBackgroundImage:shareBtnIcon forState:UIControlStateNormal]; 

     [shareButton addTarget:self action:@selector(shareButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; 

     //Create BarButton using ImageButton 
     UIBarButtonItem *shareBarBtn = [[UIBarButtonItem alloc] initWithCustomView:shareButton]; 

     //Add BarButton to NavigationBar 
     self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:shareBarBtn, nil]; 

//method for share butto click 
-(void) shareButtonClicked:(UIButton*)sender 
{ 
    NSLog(@"you clicked on share button %ld"); 
} 
相關問題