display badge info on UITableView

2020-07-18 05:29发布

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.

标签: iphone
3条回答
祖国的老花朵
2楼-- · 2020-07-18 06:12

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楼-- · 2020-07-18 06:17

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.

查看更多
Rolldiameter
4楼-- · 2020-07-18 06:20

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

enter image description here

查看更多
登录 后发表回答