1. 程式人生 > >系統導航欄左右上角按鈕如何不需要定義就可以新增小紅點

系統導航欄左右上角按鈕如何不需要定義就可以新增小紅點

最近做一個需求,要在系統導航欄右上角按鈕加上一個小紅點,以前博主習慣使用自定義導航欄,所以並不怎麼和系統的東西打交道,那怎麼辦?求助度娘唄,查了一會,都是自定義按鈕,也沒什麼比較快捷的方法,於是就自己去看系統UIBarButtonItem,這一看不打緊,還真讓博主找到了辦法。

有這麼一個屬性:

@property(nullable, nonatomic,strong)  __kindof UIView     *customView;       // default is nil

預設為nil,當建立了UIBarButtonItem之後就存在了,所以我們是不是可以直接把紅點加在這個customView上面?

於是進行了如下嘗試;

UIBarButtonItem *saveItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"xxxxxx" target:self action:@selector(xxxxxxAction)];
self.navigationItem.rightBarButtonItem = saveItem;

UIView *redPoint = [[UIView alloc] initWithFrame:CGRectMake:(x, y, width, height)];
redPoint.backgroundColor
= [UIColor red]; redPoint.layer.cornerRadius = 3; redPoint.clipsToBounds = YES; [saveItem.customView addSubview:redPoint];

哈,竟然成功了,如果需要刪除這個點也很簡單,直接:

//redPoint寫成全域性即可
[redPoint removeFromSuperview];

意外之喜,免了自定義的麻煩,而且可控度還非常高。

還有一種比較好的用法就是擴充套件UIBarButtonItem這個類,直接加上紅點,增加布爾值直接控制,是不是很簡單呢?