-->

display badge info on UITableView

2020-07-18 06:00发布

问题:

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

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.

回答1:

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.



回答2:

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);


回答3:

You can get the following out put using the code in Link



标签: iphone