iOS – 添加徽章到UITableViewCell

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

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

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

这是对@ POF的答案的一个迅速增强。 我们不需要那么多的子视图,我们可以使用math来支持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徽章

TDBadgedCell是一个不错的select。 高度可定制您的需求。

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

而我的结果是:

在这里输入图像说明

希望能帮助到你。

是的,目前还没有支持向UITableView Cell添加徽章的方法。 在这个例子中,它很可能是一个包含图像和UILabel的自定义子视图。

我想添加另一个替代品来创build自定义的徽章。 CustomBadgefunction稍强一些。 它是开放的和免费的。