Displaying notification badge like counter in UINavigationbar

我的未来我决定 提交于 2019-12-02 05:56:47

You need to create a UIBarButtonItem that contains a custom view using initWithCustomView. The custom view could be a custom UIButton with a number badge as subview. With this custom view you can also control the width of the buttons.

There is no public API to create a notification badge directly. In case of a tab bar item you could set a badge using the property badgeValue - but not with UIBarButtonItem. Here you need to use this open source control: MKNumberBadgeView.

Note that the property rightBarButtonItems is available since iOS 5. If you only need one item set the rightBarButtonItem instead.

UIButton * buttton = [UIButton buttonWithType:UIButtonTypeCustom];
[buttton setFrame:CGRectMake(285, 20, 20, 20)];
[buttton.layer setCornerRadius:10];
[buttton setTitle:@"23" forState:UIControlStateNormal];
[buttton.titleLabel setFont:[UIFont systemFontOfSize:12]];
[buttton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[buttton setBackgroundColor:[UIColor whiteColor]];
[self.navigationController.view addSubview:buttton];

First get the respective barbuttonitem in navigationController by

let baritem = navigationItem.right/leftBarButtonItem
baritem.badgeValue = "\(correspondingValues)"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!