【发布时间】:2010-10-18 09:17:31
【问题描述】:
如何向UITableViewCell 添加徽章,如下所示:
alt text http://img17.imageshack.us/img17/9974/img0001ac9.png
我应该简单地添加一个带有文本和标签的子视图吗?
【问题讨论】:
-
Here 是我自己的替代品。享受吧!
标签: ios objective-c uitableview
如何向UITableViewCell 添加徽章,如下所示:
alt text http://img17.imageshack.us/img17/9974/img0001ac9.png
我应该简单地添加一个带有文本和标签的子视图吗?
【问题讨论】:
标签: ios objective-c uitableview
这是对@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
}
结果(我使用品牌颜色,但您的可以是任何颜色):
【讨论】:
TDBadgedCell 是个不错的选择。高度可定制以满足您的需求。
【讨论】:
对我来说最简单的方法是使用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 单元格的方式。在这个例子中,它很可能是一个包含图像和 UILabel 的自定义子视图。
【讨论】:
我想添加另一种方法来创建自定义徽章。 CustomBadge 更强大一点。它是免费开放的。
【讨论】: