tags:

views:

82

answers:

2

I hope to display the badge info on the row UITableView like the picture shown below

alt text

I try to use codes below:

UILabel *labelCell1 =[ [UILabel alloc]init];
labelCell1.frame = CGRectMake(160.9f,10.0f,60.0f,30.0f) ;
[labelCell1 setBackgroundColor:[UIColor 
    colorWithPatternImage:[[UIImage imageNamed:@"block.png"] 
    stretchableImageWithLeftCapWidth:0.0 topCapHeight:0.0]]]; 

but I can not get result of round block shown in the picture above.

A: 

You can use the layer to make sure your label has rounded corners like the example. You also need to adjust the rect for the label based on the width of the text:

// set the text on the badge
labelCell1.text=[NSString stringWithFormat:@"%d", value];

// set the rounded corners on the layer
CALayer* layer=labelCell1.layer;
layer.masksToBounds = YES;
layer.cornerRadius = 9.0;

// adjust the width of the badge rect based on the text width
CGFloat textWidth=[labelCell1.text sizeWithFont:labelCell1.font].width+12;

labelCell1.frame=CGRectMake(
    labelCell1.frame.origin.x + labelCell1.frame.size.width - textWidth,
    labelCell1.frame.origin.y,
    textWidth,
    labelCell1.frame.size.height);
Cannonade
+1  A: 

Throw out your code, don't reinvent the wheel. This has been done by several people who have made it open source. Here is one, here is another.

coneybeare