如何在 UIBarbutton 项目上添加徽章?

发布于 2024-11-02 01:59:14 字数 96 浏览 6 评论 0原文

嗨,朋友们,我是 iPhone 开发新手。我正在努力在右侧的 UIBarbutton 项目上添加徽章值。我已经尝试过,但无法解决这个问题。谁能帮助我。

提前致谢!

Hi friends am new to iphone developing. Am struggle with add badge values on UIBarbutton item on right side. I have tried but i can't solve this problem. Can anyone help me.

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

杯别 2024-11-09 01:59:14

我知道这篇文章已经很老了,但是在 iOS7 中,MKNumberBadgeView 的外观与选项卡栏项目徽章设计并不真正匹配。
我发现这个继承 UIBarButtonItem 并很好地完成工作的另一个组件:

https://github.com/TanguyAladenise/BBBadgeBarButtonItem

希望这可能会帮助像我这样的其他 iOS7 开发者

I know this post is pretty old but with iOS7, MKNumberBadgeView's appearance does not really match the tab bar item badge design.
I have found this other component which herits UIBarButtonItem and do the job very well :

https://github.com/TanguyAladenise/BBBadgeBarButtonItem

Hope this may help other iOS7 developers like me

奶气 2024-11-09 01:59:14

最后我找到了在 UIBarbutton 项目上添加徽章的方法。我搜索了很多但没有找到正确的答案。所以我创建了 UIButton 并将其添加为 rightbarbutton 项目上的自定义视图。添加 MKNumberBadgeView 用于显示徽章编号。下面我为您添加了我的代码。

// Initialize NKNumberBadgeView...
MKNumberBadgeView *number = [[MKNumberBadgeView alloc] initWithFrame:CGRectMake(60, 00, 30,20)];
number.value = 10;

// Allocate UIButton
UIButton *btn = [UIButton  buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 70, 30);
    btn.layer.cornerRadius = 8;
    [btn setTitle:@"Button" forState:UIControlStateNormal];
    [btn addTarget:self action:nil forControlEvents:UIControlEventTouchUpInside];
    //[btn setBackgroundColor:[UIColor blueColor]];
    [btn setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.1 alpha:0.2]];
    btn.font = [UIFont systemFontOfSize:13];
    //[btn setFont:[UIFont systemFontOfSize:13]];
    [btn addSubview:number]; //Add NKNumberBadgeView as a subview on UIButton

// Initialize UIBarbuttonitem...
UIBarButtonItem *proe = [[UIBarButtonItem alloc] initWithCustomView:btn];
self.navigationItem.leftBarButtonItem = proe;

谢谢。

Finally i found the way to add badges on UIBarbutton item. I searched lot but not found the correct answer. So i created UIButton and add it as a Custom view on rightbarbutton item. Add add the MKNumberBadgeView for display the badge number. Below i have add my code for you.

// Initialize NKNumberBadgeView...
MKNumberBadgeView *number = [[MKNumberBadgeView alloc] initWithFrame:CGRectMake(60, 00, 30,20)];
number.value = 10;

// Allocate UIButton
UIButton *btn = [UIButton  buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 70, 30);
    btn.layer.cornerRadius = 8;
    [btn setTitle:@"Button" forState:UIControlStateNormal];
    [btn addTarget:self action:nil forControlEvents:UIControlEventTouchUpInside];
    //[btn setBackgroundColor:[UIColor blueColor]];
    [btn setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.1 alpha:0.2]];
    btn.font = [UIFont systemFontOfSize:13];
    //[btn setFont:[UIFont systemFontOfSize:13]];
    [btn addSubview:number]; //Add NKNumberBadgeView as a subview on UIButton

// Initialize UIBarbuttonitem...
UIBarButtonItem *proe = [[UIBarButtonItem alloc] initWithCustomView:btn];
self.navigationItem.leftBarButtonItem = proe;

Thanks.

风流物 2024-11-09 01:59:14

phyzalis 有一个很好的答案,这里有他的解决方案的分类版本:

UIBarButtonItem+Badge

下面是如何使用它:

// Build your regular UIBarButtonItem with Custom View
UIImage *image = [UIImage imageNamed:@"someImage"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0,0,image.size.width, image.size.height);
[button addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchDown];
[button setBackgroundImage:image forState:UIControlStateNormal];

// Make BarButton Item
UIBarButtonItem *navLeftButton = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = navLeftButton;

// this is the key entry to change the badgeValue
self.navigationItem.leftBarButtonItem.badgeValue = @"1";

phyzalis has a good answer, there's a categorized version of his solution here:

UIBarButtonItem+Badge

Here's how you can use it:

// Build your regular UIBarButtonItem with Custom View
UIImage *image = [UIImage imageNamed:@"someImage"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0,0,image.size.width, image.size.height);
[button addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchDown];
[button setBackgroundImage:image forState:UIControlStateNormal];

// Make BarButton Item
UIBarButtonItem *navLeftButton = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = navLeftButton;

// this is the key entry to change the badgeValue
self.navigationItem.leftBarButtonItem.badgeValue = @"1";
懷念過去 2024-11-09 01:59:14

我做了与 MaxMa 类似的操作,但我只是继续将徽章直接添加到 self.navigationController.navigationBar 中。

在此处输入图像描述

MKNumberBadgeView *numberBadge = [[MKNumberBadgeView alloc] initWithFrame:CGRectMake(35, 0, 40, 40)];
numberBadge.value = 1;

[self.navigationController.navigationBar addSubview:numberBadge];

只需确保在 viewWillDisappear 期间将其从子视图中删除,并在 viewDidAppear 期间将其添加回来。它看起来仍然有点 hacky,但我对这个 hack 比更改导航栏 z 顺序更舒服。

在 viewWillDisappear 期间将其删除

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [numberBadge removeFromSuperview]; 
}

I did something similar to MaxMa, but I just went ahead and added the badge directly to the self.navigationController.navigationBar.

enter image description here

MKNumberBadgeView *numberBadge = [[MKNumberBadgeView alloc] initWithFrame:CGRectMake(35, 0, 40, 40)];
numberBadge.value = 1;

[self.navigationController.navigationBar addSubview:numberBadge];

Just make sure to remove it from the subview during viewWillDisappear and add it back during viewDidAppear. It still seems a little hacky, but I'm more comfortable with this hack then changing the nav bar z-order.

To remove it during viewWillDisappear

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [numberBadge removeFromSuperview]; 
}
秋日私语 2024-11-09 01:59:14

这很简单,也是最好的方法!

在此处输入图像描述

MKNumberBadgeView *numberBadge = [[MKNumberBadgeView alloc] initWithFrame:CGRectMake(230, -51, 40, 40)];
numberBadge.value = 5;

self.navigationController.navigationBar.layer.zPosition = -1;
[self.view addSubview:numberBadge];

It's simple and the best way !

enter image description here

MKNumberBadgeView *numberBadge = [[MKNumberBadgeView alloc] initWithFrame:CGRectMake(230, -51, 40, 40)];
numberBadge.value = 5;

self.navigationController.navigationBar.layer.zPosition = -1;
[self.view addSubview:numberBadge];
小猫一只 2024-11-09 01:59:14

针对 Swift 3 进行了更新:

使用下面的简单代码在 UIBarButtonItem 上添加徽章;

// Variable Declartion

var badgeCount = Int()

// Instance Method

    func setUpBadgeCountAndBarButton() {
        // badge label
        let label = UILabel(frame: CGRect(x: 10, y: -05, width: 25, height: 25))
        label.layer.borderColor = UIColor.clear.cgColor
        label.layer.borderWidth = 2
        label.layer.cornerRadius = label.bounds.size.height / 2
        label.textAlignment = .center
        label.layer.masksToBounds = true
        label.textColor = .white
        label.font = label.font.withSize(12)
        label.backgroundColor = .red
        label.text = "\(self.badgeCount)"

        // button
        let rightButton = UIButton(frame: CGRect(x: 0, y: 0, width: 35, height: 35))
        rightButton.setBackgroundImage(UIImage(named: "notification_dash"), for: .normal)
        rightButton.addTarget(self, action: #selector(notificationBarButtonClick), for: .touchUpInside)
        rightButton.addSubview(label)

        // Bar button item
        let rightBarButtomItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem = rightBarButtomItem
    }

// Call To Method

self.badgeCount = 11
self.setUpBadgeCountAndBarButton()

//注意:根据您收到的通知增加您的徽章。您必须根据您决定的逻辑编写代码,即如何在数据库中维护该徽章计数。

享受..!

Updated for Swift 3:

use below simple code to add the badge on UIBarButtonItem;

// Variable Declartion

var badgeCount = Int()

// Instance Method

    func setUpBadgeCountAndBarButton() {
        // badge label
        let label = UILabel(frame: CGRect(x: 10, y: -05, width: 25, height: 25))
        label.layer.borderColor = UIColor.clear.cgColor
        label.layer.borderWidth = 2
        label.layer.cornerRadius = label.bounds.size.height / 2
        label.textAlignment = .center
        label.layer.masksToBounds = true
        label.textColor = .white
        label.font = label.font.withSize(12)
        label.backgroundColor = .red
        label.text = "\(self.badgeCount)"

        // button
        let rightButton = UIButton(frame: CGRect(x: 0, y: 0, width: 35, height: 35))
        rightButton.setBackgroundImage(UIImage(named: "notification_dash"), for: .normal)
        rightButton.addTarget(self, action: #selector(notificationBarButtonClick), for: .touchUpInside)
        rightButton.addSubview(label)

        // Bar button item
        let rightBarButtomItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem = rightBarButtomItem
    }

// Call To Method

self.badgeCount = 11
self.setUpBadgeCountAndBarButton()

//Note: Increase your badge as per you received notification.You have to write your code as per your decided your logic i.e. how to maintain that badge count number in database.

Enjoy..!

爱殇璃 2024-11-09 01:59:14

我知道这个问题已经解决了,但为了完整起见,我想我可以将我发现的内容添加到这个答案中。

您还可以直接将 MKNumberBadgeView 添加到 UIBarButtonItem 的视图中。使用 Monotouch (C#),这就是获取 UIBarButtonItem 视图的方法,

        //barbutton is some UIBarButtonItem. Make sure to check for view. In
        //ViewDidLoad(), the view for the barbutton might not exist yet.
        Selector sel = new Selector("view");
        var handle = Messaging.intptr_objc_msgSend(barbutton.Handle, sel.Handle);
        var view = Runtime.GetNSObject(handle) as UIView;
        var mkBadge = ...    //the badge
        view.Add(badge);
        view.Layer.ZPosition = <some large number> 

我确信将其转换为 Obj-C 很容易。您还需要调整徽章的框架,使其显示在正确的位置。

这样您就不必从导航栏中删除/添加视图。

I know this has been solved already,but I thought I might add what I have discovered to this answer for the sake of completeness.

You can also just add MKNumberBadgeView directly to the view for the UIBarButtonItem. Using Monotouch (C#), this is how you get the view for the UIBarButtonItem

        //barbutton is some UIBarButtonItem. Make sure to check for view. In
        //ViewDidLoad(), the view for the barbutton might not exist yet.
        Selector sel = new Selector("view");
        var handle = Messaging.intptr_objc_msgSend(barbutton.Handle, sel.Handle);
        var view = Runtime.GetNSObject(handle) as UIView;
        var mkBadge = ...    //the badge
        view.Add(badge);
        view.Layer.ZPosition = <some large number> 

I'm sure it's easy to convert this to Obj-C. You will also need to play around with the Frame for the badge to get it to show up in the right place.

This way you wont have to remove/add the view from the navigationbar.

断肠人 2024-11-09 01:59:14

在搜索了太多解决方案后,我找到了 Objective-C 的最佳解决方案

转到以下链接并下载两个文件 "UIBarButtonItem+Badge.h""UIBarButtonItem+Badge.m"并添加到您的项目中:

https://github.com/mikeMTOL/UIBarButtonItem-Badge

然后在你的类中导入:

#import "UIBarButtonItem+Badge.h"

并写下以下行来添加徽章:

self.navigationItem.rightBarButtonItem.badgeValue = @"1"; //your value 

希望它能工作!

After searching too many solutions I found this best solution for Objective-C

Goto Following Link and download two files "UIBarButtonItem+Badge.h" and "UIBarButtonItem+Badge.m" and add to your project :

https://github.com/mikeMTOL/UIBarButtonItem-Badge

Then import in your class :

#import "UIBarButtonItem+Badge.h"

And write down following line to add badge :

self.navigationItem.rightBarButtonItem.badgeValue = @"1"; //your value 

Hope it will Work !!!

罗罗贝儿 2024-11-09 01:59:14

这是一个简单的 Swift 4 解决方案(带有一些自定义) https://github.com/Syngmaster/BadgedBarButtonItem< /a>

只需将类拖放到您的项目中,您就可以像这样使用它:

class ViewController: UIViewController {

    let btn = BadgedButtonItem(with: UIImage(named: "your_image"))

    override func viewDidLoad() {
        super.viewDidLoad()

        btn.badgeTextColor = .black
        btn.badgeTintColor = .yellow
        btn.position = .right
        btn.hasBorder = true
        btn.borderColor = .red
        btn.badgeSize = .medium
        btn.badgeAnimation = true

        self.navigationItem.rightBarButtonItem = btn

        btn.tapAction = {
            self.btn.setBadge(with: 4)
        }

    }

}

Here is a simple Swift 4 solution for it (with some customisation) https://github.com/Syngmaster/BadgedBarButtonItem

Just drag and drop the class into your project and you can use it like that:

class ViewController: UIViewController {

    let btn = BadgedButtonItem(with: UIImage(named: "your_image"))

    override func viewDidLoad() {
        super.viewDidLoad()

        btn.badgeTextColor = .black
        btn.badgeTintColor = .yellow
        btn.position = .right
        btn.hasBorder = true
        btn.borderColor = .red
        btn.badgeSize = .medium
        btn.badgeAnimation = true

        self.navigationItem.rightBarButtonItem = btn

        btn.tapAction = {
            self.btn.setBadge(with: 4)
        }

    }

}
寻梦旅人 2024-11-09 01:59:14

添加 UIActivityIndi​​catorView 而不替换 UIBarButtonItem 的扩展。

extension UIBarButtonItem {
    
    func startLoading() {
        guard let view = self.value(forKey: "view") as? UIView else { return }
        let loading = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        loading.frame = view.bounds
        loading.startAnimating()
        view.addSubview(loading)
        view.bringSubview(toFront: loading)
        let buttonView = view.subviews.first
        buttonView?.alpha = 0.1
    }
    
    func stopLoading() {
        guard let view = self.value(forKey: "view") as? UIView else { return }
        let loading = view.subviews.filter({ $0 is UIActivityIndicatorView }).first
        loading?.removeFromSuperview()
        let buttonView = view.subviews.first
        buttonView?.alpha = 1.0
    }
    
}

Extension to add an UIActivityIndicatorView without replacing the UIBarButtonItem.

extension UIBarButtonItem {
    
    func startLoading() {
        guard let view = self.value(forKey: "view") as? UIView else { return }
        let loading = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        loading.frame = view.bounds
        loading.startAnimating()
        view.addSubview(loading)
        view.bringSubview(toFront: loading)
        let buttonView = view.subviews.first
        buttonView?.alpha = 0.1
    }
    
    func stopLoading() {
        guard let view = self.value(forKey: "view") as? UIView else { return }
        let loading = view.subviews.filter({ $0 is UIActivityIndicatorView }).first
        loading?.removeFromSuperview()
        let buttonView = view.subviews.first
        buttonView?.alpha = 1.0
    }
    
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文