leftBarbuttonItem/rightBarButtonItem和leftBarbuttonItems/rightBarButtonItems相關問題


  仿寫項目的時候,出現了一個Bug:點擊右邊的"編輯","編輯"變為"完成",左側出現"全選","刪除"等按鈕,再點擊"完成",本應該把左側出現的按鈕都隱藏掉,並把"完成"再次改為"編輯",但是左側的按鈕並沒有隱藏掉.

  正確的需求應該如下圖所示:

  

  出現Bug的效果圖:

 

  有Bug的核心代碼部分如下:

 1 //右側按鈕點擊事件
 2 - (void)rightClick:(UIBarButtonItem *)item{
 3     if ([item.title isEqualToString:@"編輯"]) {
 4         item.title = @"完成";
 5         //左側顯示 返回 全選 全不選 刪除
 6         self.navigationItem.leftBarButtonItems = @[self.backItem,self.selectAllItem,self.unselectAllItem,self.deleteItem];
 7         
 8     }else{
 9         item.title = @"編輯";
10         //左側只顯示 返回
11         self.navigationItem.leftBarButtonItem = self.backItem;
12         
13     }
14     //刷新
15     [self.collectionView reloadData];
16 }

  一進入控制器就設置navigationItem的代碼部分:

 1 - (void)setUpNav{
 2     //設置左側
 3     self.navigationItem.leftBarButtonItem = self.backItem;
 4     
 5     //設置右側
 6     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"編輯" style:UIBarButtonItemStylePlain target:self action:@selector(rightClick:)];
 7     
 8     //標題
 9     self.title = @"收藏";
10     
11 }

 

  將所有的leftBarButtonItem改為leftBarButtonItems,即使只有一個元素,也寫作Items,bug就不見了,代碼如下圖(為了突出重點,選擇截圖做展示)

 

  個人總結:在設置UINavigationBar過程中,只要一個地方需要使用left/rightBarButtonItems,那么就把所有的地方都寫成left/rightBarButtonItems.

  個人推理(非官方,如果有錯歡迎指正),因為left/rightBarButtonItems和left/rightBarButtonItem是navigationItem的兩個獨立的屬性,並且如果遇到二者都有值的時候,數組(left/rightBarButtonItems)的優先級可能要比left/rightBarButtonItem的優先級高一些.編譯器會優先選擇left/rightBarButtonItems中的元素來布局.

 

  查看蘋果官方頭文件UINavigationBar.h,相關語句紅框圈出:

 

  The older single properties (leftBarButtonItem and rightBarButtonItem) now refer to the first item in the respective array of items.

  翻譯(不專業,但大體意思應該沒錯):之前的單數屬性(leftBarButtonItem 和 rightBarButtonItem)現在指各自的items數組中的首個元素.

  NOTE: You'll achieve the best results if you use either the singular properties or the plural properties consistently and don't try to mix them.

  翻譯概述(不專業,但大體意思應該沒錯):NOTE:想要得到最好的結果,最好要么一直用單數屬性要么一直用復數屬性,不要試圖把他們混起來用.

 

 

(原創,轉載請注明出處.有錯誤的地方歡迎指正.)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM