Search code examples
iphoneioscocoa-touchcore-animationcalayer

CALayer not rendering or drawing


I have a subclassed UIButton inside a subclassed UITableViewCell. The button is loaded from a nib.

I have an image I want to use as the image for the button. I would like to use CALayer for more control over animation. When the user taps the button, animation will occur. But, I can't even get the image to show up.

QuartzCore is imported.

Code of my subclassed UIButton (always loaded from a nib):

-(void)awakeFromNib {
    [super awakeFromNib];
    self.clipsToBounds = NO;
    self.backgroundColor = [UIColor clearColor];
    self.opaque = NO;
    self.userInteractionEnabled = YES;
}

Code in the table view controller:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyCustomCell *cell = (BLCustomCellCenter*)[tableView dequeueReusableCellWithIdentifier:@"customCellID"];
    if (cell == nil) {
        // ... cell is initialized
    }

    // configure the image for the button
    //
    // Note:  there is an outlet to the UIButton called 'customButton' 

    CALayer *imgLayer = [CALayer layer];
    imgLayer.bounds = CGRectMake(0, 0, cell.customButton.bounds.size.width, cell.customButton.bounds.size.height);
    imgLayer.position = CGPointMake(cell.customButton.bounds.size.width/2, cell.customButton.bounds.size.height/2);
     UIImage *img = [UIImage imageNamed:@"someImage"];
    imgLayer.contents = (id)[img CGImage];
    [cell.customButton.layer addSublayer:imgLayer];

    // ... configure subviews of 'customButton'

    return cell;
}

Any help very much appreciated, as always.


Solution

  • Figured it out, after hours of debugging. The thing (that perhaps I forgot to mention) was that the custom UITableViewCell was loaded from a nib. The subview I wanted to view was also loaded from a nib. So, it's a nib within a nib.

    Per this wonderful article, overriding awakeAfterUsingCoder: inside the subview's class did the trick. When loading the parent nib, the super's initUsingCoder:is called on the subview which loads only a placeholder object.

    This 'placeholder' object was causing my problems as I was manipulating the placeholder instead of the actual object I wanted.

    Therefore, you have to load and initialize the subview's objects from the nib, and you do this by overriding NSObject's awakeAfterUsingCoder:.