iOS开发 - 系统导航栏左右上角按钮如何不需要定义就可以添加小红点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/CodingFire/article/details/82667544

最近做一个需求,要在系统导航栏右上角按钮加上一个小红点,以前博主习惯使用自定义导航栏,所以并不怎么和系统的东西打交道,那怎么办?求助度娘呗,查了一会,都是自定义按钮,也没什么比较快捷的方法,于是就自己去看系统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这个类,直接加上红点,增加布尔值直接控制,是不是很简单呢?

猜你喜欢

转载自blog.csdn.net/CodingFire/article/details/82667544