Search code examples
objective-ciosuibuttoncalayer

UIButton Doesn't Detect Touches After Custom CALayer Assignment


My UIButton's target action doesn't get called unless the delegate assignment below is commented out, but then I lose my custom drawing. What am I missing?

- (void)createLayerForPaletteAtIndex:(int)paletteIndex onButton:(UIButton *)button
{
    self.colorPaletteLayer            = button.layer;
    self.colorPaletteLayer.delegate   = self; // Must implement drawLayer:inContext
    NSString *stringForIndex          = [NSString stringWithFormat:@"%d",paletteIndex];
    self.colorPaletteLayer.name       = stringForIndex;
    button.clearsContextBeforeDrawing = YES;
    button.layer.opaque               = YES;
    [self.colorPaletteLayer setNeedsDisplay]; // Calls drawLayer:inContext
}

Solution

  • You're hijacking the button's layer. You should not do that. UIKit does not expect you to do so. You should create a sub-layer and add it to the button's layer.