【问题标题】:iOS - Add Badge to UITableViewCelliOS - 将徽章添加到 UITableViewCell
【发布时间】:2010-10-18 09:17:31
【问题描述】:

如何向UITableViewCell 添加徽章,如下所示:

alt text http://img17.imageshack.us/img17/9974/img0001ac9.png

我应该简单地添加一个带有文本和标签的子视图吗?

【问题讨论】:

  • Here 是我自己的替代品。享受吧!

标签: ios objective-c uitableview


【解决方案1】:

这是对@POF 答案的快速改进。我们不需要那么多子视图,我们可以使用数学来支持 N 位数,而不仅仅是 1-3:

func setDiscountBadge(count: Int) {
  let size: CGFloat = 26
  let digits = CGFloat( count("\(number)") ) // digits in the label
  let width = max(size, 0.7 * size * digits) // perfect circle is smallest allowed
  let badge = UILabel(frame: CGRectMake(0, 0, width, size))
  badge.text = "\(number)"
  badge.layer.cornerRadius = size / 2
  badge.layer.masksToBounds = true
  badge.textAlignment = .Center
  badge.textColor = UIColor.whiteColor()
  badge.backgroundColor = cfg.UIColors.brand
  YOURCELL.accessoryView = badge // !! change this line
}

结果(我使用品牌颜色,但您的可以是任何颜色):

【讨论】:

    【解决方案2】:

    TDBadgedCell 是个不错的选择。高度可定制以满足您的需求。

    【讨论】:

      【解决方案3】:

      对我来说最简单的方法是使用cell.accessoryView。请查看我的代码我是如何做到的:

      UIImageView * commentsViewBG = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @"counter1.png"]];
      commentsViewBG.frame = CGRectMake(
          commentsViewBG.frame.origin.x,
          commentsViewBG.frame.origin.y, 30, 20);
      
      
      UILabel *commentsCount;
      if (commentsArray.totalCount < 10)
          commentsCount = [[UILabel alloc]initWithFrame:CGRectMake(10, -10, 40, 40)];
      else if (commentsArray.totalCount < 100)
          commentsCount = [[UILabel alloc]initWithFrame:CGRectMake(5, -10, 40, 40)];
      else if (commentsArray.totalCount < 1000)
      {
          commentsViewBG.frame = CGRectMake(
              commentsViewBG.frame.origin.x,
              commentsViewBG.frame.origin.y, 40, 20);
          commentsCount = [[UILabel alloc]initWithFrame:CGRectMake(5, -10, 40, 40)];
      }
      commentsCount.text = [NSString stringWithFormat:@"%ld",(long)commentsArray.totalCount];
      commentsCount.textColor = [UIColor whiteColor];
      commentsCount.backgroundColor = [UIColor clearColor];
      [commentsViewBG addSubview:commentsCount];
      cell.accessoryView = commentsViewBG;
      

      我的结果:

      希望对你有帮助。

      【讨论】:

      • 请不要对多个问题发布完全相同的答案:它要么不适合所有人,要么问题是重复的,应该这样标记/关闭。
      • 如果它更容易找到,我看不出有什么问题。有时重复的问题会首先出现在 Google 上,即使它们被标记,有时也可以得到更好的答案。
      【解决方案4】:

      是的,目前尚不支持将徽章添加到 UITableView 单元格的方式。在这个例子中,它很可能是一个包含图像和 UILabel 的自定义子视图。

      【讨论】:

        【解决方案5】:

        我想添加另一种方法来创建自定义徽章。 CustomBadge 更强大一点。它是免费开放的。

        【讨论】:

          猜你喜欢
          • 2012-03-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-04
          • 2019-08-31
          • 1970-01-01
          相关资源
          最近更新 更多