8

I'm adding a UILabel to each cell in my table view. This presents no problem initially. When I round the corners of the UILabel using layer.cornerRadius scrolling the table view grinds to a halt.

 UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(cell.bounds.origin.x+10 ,5, 30, 30)];
 label1.backgroundColor = ([[managedObject valueForKey:@"color"] hasPrefix:@"FFFFFF"]) ? [UIColor blackColor] : color;
 label1.layer.cornerRadius = 10.0f;
 [cell addSubview:label1];
Stuart
  • 36,683
  • 19
  • 101
  • 139
yesimarobot
  • 283
  • 7
  • 16
  • You might want to see [how Tweetie does it](http://blog.atebits.com/2008/12/fast-scrolling-in-tweetie-with-uitableview/) (scrolls smoothly). – icktoofay Feb 13 '10 at 05:55

3 Answers3

15

There is no need for an image with rouned corners - see the answer by fknrdcls to this question:

UILabel layer cornerRadius negatively impacting performance

Basically, you simply need to give your label a transparent background, and add the backgroundcolor to the layer instead. Then, you can disable maskToBounds, which greatly improves performance. So your code becomes:

UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(cell.bounds.origin.x+10 ,5, 30, 30)];
label1.backgroundColor = [UIColor clearColor];
label1.layer.backgroundColor=[UIColor whiteColor].CGColor;
label1.layer.cornerRadius = 10.0f;
label1.layer.masksToBounds = NO;
label1.layer.shouldRasterize = YES;
Community
  • 1
  • 1
ChristophK
  • 3,157
  • 2
  • 25
  • 29
  • +1 I really like this solution, but I need **only some corners rounded**. My workaround is: To 'show' only top and bottom right corners, I add a subview with a negative value on its `frame.origin.x` and assign the `cornerRadius` to its `layer`. If someone found a better solution for that need, I'm interested. – anneblue Mar 04 '14 at 12:02
7

I've tried this before myself and found that it's useless for any kind of view that moves. You should create an image with rounded corners and add that as the background of your label instead.

nevan king
  • 112,709
  • 45
  • 203
  • 241
  • this is not a really good solution because on different size labels, image will get stretched and that corner radius given by the image will differ from the others.. – Silviu St Jul 30 '14 at 08:54
0

for an UIImageView the UILabel trick didn't work because I had to crop an image as well, not just a background color. the quickest solution I found was to rasterize the view's parent whenever I animated it (I have a sliding panel).

rosem
  • 1,311
  • 14
  • 19