【问题标题】:How to add Badges on UIBarbutton item?如何在 UIBarbutton 项目上添加徽章?
【发布时间】:2011-04-16 05:14:52
【问题描述】:

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

提前致谢!

【问题讨论】:

    标签: ios uinavigationbar uibarbuttonitem badge


    【解决方案1】:

    我知道这篇文章已经很老了,但是在 iOS7 中,MKNumberBadgeView 的外观与标签栏项目的徽章设计并不完全匹配。 我发现这个继承 UIBarButtonItem 并且做得很好的另一个组件:

    https://github.com/TanguyAladenise/BBBadgeBarButtonItem

    希望这可以帮助像我这样的其他 iOS7 开发人员

    【讨论】:

      【解决方案2】:

      最后我找到了在 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;
      

      谢谢。

      【讨论】:

      • 这段代码的结果创建了一个非常丑陋的按钮(但它确实有效)。您已被警告;)
      • 这在 iOS 5 上效果更好,因为您可以更好地控制按钮的外观。否则,您最终会在导航栏中看到难看的按钮。
      【解决方案3】:

      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";
      

      【讨论】:

      • 我遇到了“在 UIBarButtonItem 上找不到属性”badgeValue”的问题?
      • 在我的应用程序的 iOS 11 中运行得非常好。唯一的问题是徽章本身不响应点击,使按钮更难点击。通过向徽章添加手势识别器来解决此问题:UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(buttonPressed)]; [self.navigationItem.rightBarButtonItem.badge addGestureRecognizer:tapGesture];
      • 从 Github 上的 lib 存储库中查看我对 iOS 11 问题的回答 github.com/mikeMTOL/UIBarButtonItem-Badge/issues/37
      【解决方案4】:

      我做了一些类似于 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]; 
      }
      

      【讨论】:

      • 如何在 viewWillDisappear 中删除它?你能添加那个代码吗?
      • 当然,我添加了示例来展示如何在视图消失时将其删除。
      【解决方案5】:

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

      MKNumberBadgeView *numberBadge = [[MKNumberBadgeView alloc] initWithFrame:CGRectMake(230, -51, 40, 40)];
      numberBadge.value = 5;
      
      self.navigationController.navigationBar.layer.zPosition = -1;
      [self.view addSubview:numberBadge];
      

      【讨论】:

      • 您依赖于框架恰好在右侧 230 处。也许添加约束或其他东西。但这基本上不适用于所有手机宽度。
      【解决方案6】:

      为 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()
      

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

      享受..!

      【讨论】:

        【解决方案7】:

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

        您也可以直接将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 很容易。您还需要使用 Frame 来让徽章显示在正确的位置。

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

        【讨论】:

          【解决方案8】:

          在搜索了太多解决方案后,我找到了 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 
          

          希望它会工作!!!

          【讨论】:

            【解决方案9】:

            在不替换 UIBarButtonItem 的情况下添加 UIActivityIndi​​catorView 的扩展。

            扩展 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
            }
            

            }

            【讨论】:

              【解决方案10】:

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

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

              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)
                      }
              
                  }
              
              }
              

              【讨论】:

                猜你喜欢
                • 2012-03-29
                • 2015-11-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2020-12-20
                • 1970-01-01
                • 1970-01-01
                • 2014-05-09
                相关资源
                最近更新 更多