【问题标题】:Displaying notification badge like counter in UINavigationbar在 UINavigationbar 中显示类似计数器的通知徽章
【发布时间】:2013-01-24 10:38:44
【问题描述】:

我需要在 iPhone 导航栏中显示待处理通知的数量。外观应该类似于通知徽章 - 但这些不是 APNS 通知。它们是从具有相似目的的私人服务器发送的。

我尝试在我的UINavigationbar 中添加一个右/左按钮 (UIBarButtonItem),但它的外观似乎非常僵硬。我无法设置它的宽度、字体等。请参阅我的代码:

  self.notifButton = [[UIBarButtonItem alloc] initWithTitle:@"0" style:
                    UIBarButtonItemStyleBordered target:self action:@selector(TouchNotif)];

 NSMutableArray *items = [[NSMutableArray alloc] init];

 [items addObject:self.notifButton];
 self.navigationItem.rightBarButtonItems = items;

由于其他 2 个项目也添加到 items 数组中,所以导航栏很混乱。它们的字体、宽度等我无法使用,或者我不知道应该如何创建它们。

我的问题:

1) 在导航栏右侧区域中容纳至少 3 个项目的正确方法是什么?我问这个是因为我找不到使用我使用的UIButtons 的宽度和字体的方法。

2) 如果我想为我的通知按钮自定义外观(就像通知徽章一样) - 是否有任何指示如何制作它?使用哪个控件,如何设置UINavigationBar内允许的框架和字体?

请帮忙。

【问题讨论】:

    标签: iphone ios uinavigationbar uibarbuttonitem


    【解决方案1】:

    您需要使用initWithCustomView 创建一个包含自定义视图的UIBarButtonItem。 自定义视图可以是带有数字徽章的自定义 UIButton 作为子视图。使用此自定义视图,您还可以控制按钮的宽度。

    没有直接创建通知徽章的公共 API。如果是标签栏项目,您可以使用属性badgeValue 设置徽章 - 但不能使用UIBarButtonItem。 这里需要用到这个开源控件:MKNumberBadgeView

    请注意,属性 rightBarButtonItems 从 iOS 5 开始可用。 如果您只需要一项,请改为设置rightBarButtonItem

    【讨论】:

    • 谢谢,也 +1。 InitWithCustomView 工作。但是,在获得所需的图像后,我无法设置 UIBarButtonItem 的标题文本。例如,在我的代码中,当我执行 self.notifButton.title = @"my title" 时,调试器显示正确,但标题在图像上不可见。怎么办?
    【解决方案2】:
    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];
    

    【讨论】:

    • 各位,希望对你们有帮助。
    【解决方案3】:

    首先通过

    获取navigationController中相应的barbuttonitem
    let baritem = navigationItem.right/leftBarButtonItem
    baritem.badgeValue = "\(correspondingValues)"
    

    【讨论】:

      猜你喜欢
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多