d11wtq
d11wtq

Reputation: 35318

Use a CALayer to add a diagonal banner/badge to the corner of a UITableViewCell

I'm trying to draw decorate a UITableViewCell in my table view with a text banner that looks like a stamp, diagonally across the top left corner of the cell.

I'm probably doing this in the wrong place entirely, but I'm overriding -layoutSubviews to add the layer. I tried to do it in -drawRect: but the banner ends up covered by the table view's imageView as the table renders (i.e. the layer is underneath the image view, as the image view is added later).

I'm really struggling to get the math right for this. I've calculated that, assuming the banner begins at 40 points from the top of the cell and 40 points from the left, angled at exactly -45º, the hypotenuse would be 56 points. So I'm making a CALayer 56 points wide, then rotating it -45º, which works. The problem is the position within the cell... it's sitting way out into the cell, instead of hard up against the edges of it.

Rather than me apply trial and error to get this in the right place, can somebody help me with the math? Obviously I need to move the layer and rotate it.

It feels like anchorPoint is what I need here, but that seems to actually move the layer around, so I must be missing the point (no pun intended).

- (void)layoutSubviews
{
    [super layoutSubviews];

    self.imageView.frame = CGRectMake(10, 10, 50, 50);

    if (self.hasBanner) {
        CALayer *banner = [CALayer layer];
        banner.backgroundColor = [UIColor colorWithRed:.5f green:.5f blue:.5f alpha:1.f].CGColor;
        banner.frame = CGRectMake(0, 40-15, 56, 15);
        banner.anchorPoint = CGPointMake(0, 1); // this just makes it worse
        banner.transform = CATransform3DMakeRotation(-45.0 / 180.0 * M_PI, 0.0, 0.0, 1.0);
        [self.layer addSublayer:banner];
    }
}

Banner sits in the wrong place

Upvotes: 3

Views: 1031

Answers (1)

Kurt Revis
Kurt Revis

Reputation: 27994

Where should the layer go?

Let's draw a diagram:

enter image description here

We could go further and do some trig, but let's stop here. It's pretty obvious that the middle-top point of the banner should be at (20,20). We can tell Core Animation to do exactly that.

Positioning the layer

Think of it in terms of four separate steps:

  1. Set the size of the layer
  2. Decide what point in the layer is a convenient reference point
  3. Set the position of that reference point
  4. Rotate the layer around the reference point

These correspond to four properties: bounds, anchorPoint, position, and transform.

You don't want to touch the frame property, because its value is derived from the bounds, position, transform, and anchorPoint. If you try to set the frame, CALayer will try to invert the transform, apply that to the rect you gave, and then set the bounds and position. That may not give the results you want, so you're better off just ignoring it entirely -- less confusing that way.

(For more information, see the Core Animation Guide, specifically the section Layer Objects Define Their Own Geometry.)

In code, we will:

  1. Set bounds to the rect 0, 0, width, height. (I'm deliberately leaving width to you -- it's going to have to be more than 56.)
  2. Set anchorPoint to the point 0.5, 0. In other words, halfway along the width of the layer, and at the top of the layer.
  3. Set position to the point 20, 20.
  4. Set transform to rotate by 45°.

By the way, in the code below, I'm setting the affineTransform instead of the transform, just because it's slightly more convenient for simple 2-D transformations.

When to set up the layer

You're correct that -drawRect: is the wrong place to create and add layers. That method should draw into the content of the view (its CGContext) but do nothing else.

layoutSubviews will work, but it will get called more often than you might expect, and you don't want to create and add a new layer each time.

It looks like you just need to set the layer's geometry once, and never touch it again. Why not just create or destroy the layer when your hasBanner property is changed?

@interface MyTableViewCell ()

@property (nonatomic) BOOL hasLayer;
@property (nonatomic) CALayer* bannerLayer;

@end

- (void)setHasBanner:(BOOL)hasBanner
{
    if (hasBanner != _hasBanner) {
        _hasBanner = hasBanner;

        if (hasBanner) {
            CALayer* banner = [CALayer layer];
            banner.backgroundColor = [UIColor colorWithRed:.5f green:.5f blue:.5f alpha:1.f].CGColor;

            banner.bounds = CGRectMake(0, 0, 56, 15);
            banner.anchorPoint = CGPointMake(0.5, 0);
            banner.position = CGPointMake(20, 20);
            banner.affineTransform = CGAffineTransformMakeRotation(-45.0 / 180.0 * M_PI);

            // Add the layer to the view, and remember it for later
            [self.layer addSublayer:banner];
            self.bannerLayer = banner;
        } else {
            // Remove the layer from the view, and discard it
            [self.bannerLayer removeFromSuperlayer];
            self.bannerLayer = nil;
        }
    }
}

Upvotes: 8

Related Questions