12

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

替代文字 http://img17.imageshack.us/img17/9974/img0001ac9.png

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

4

5 回答 5

5

这是对@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
}

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

uilabel 徽章

于 2015-06-03T07:51:12.903 回答
2

至于我最简单的方法是使用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;

我的结果:

在此处输入图像描述

希望能帮助到你。

于 2014-01-12T15:15:13.303 回答
2

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

于 2014-06-06T01:26:15.363 回答
1

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

于 2009-06-23T21:36:21.333 回答
1

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

于 2011-05-11T11:50:26.633 回答