2009-04-08 68 views

回答

1

是的,目前還沒有支持向UITableView Cell添加徽章的方式。在這個例子中,它很可能是一個包含圖像和UILabel的自定義子視圖。

1

我想添加另一個替代方案來創建自定義徽章。 CustomBadge有點強大。它是開放的和免費的。

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; 

我的結果:

enter image description here

希望它能幫助。

+0

請不要在多個問題上發佈完全相同的答案:它不是很適合所有人,或者問題是應該標記/關閉的重複問題。 – 2014-01-12 15:28:32

2

TDBadgedCell是一個不錯的選擇。高度可定製您的需求。

4

這是對@ 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 badge