0

I'm trying to do draw a fancy UIButton using Quartz. I've declared my own button class like this:

@interface MyButton : UIButton
@end

In the .m file I'm constructing the button:

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        // Initialization code
        CALayer *buttonLayer = self.layer;
        buttonLayer.masksToBounds = YES;

        CALayer *customDrawn = [CALayer layer];
        customDrawn.delegate = self;
        customDrawn.masksToBounds = YES;
        [buttonLayer insertSublayer:customDrawn atIndex:0];
        [customDrawn setNeedsDisplay];
    }
    return self;
}

But this results in some kind of recursion and finally fails with a EXC_BAD_ACCESS.

I've implemented a method drawLayer: inContext:, but it still crashes. The only way I can avoid the crash is by removing the delegate-assignment, but then I can't do any of the custom drawing I want to implement.

How can I make this work?

Thorsten
  • 12,921
  • 17
  • 60
  • 79
  • post lunch food comma so I withdrew my answer, but I don't see any circular reference in your posted code – ethyreal Jun 05 '12 at 20:48
  • 1
    See [this answer to a very similar question](http://stackoverflow.com/questions/2015353/using-calayer-delegate). – Kurt Revis Jun 06 '12 at 02:19

1 Answers1

0

As described in the question mentioned by Kurt Revis, a UIView (such as UIButton) can't be used as a delegate for a sublayer. (It is already the delegate for the "main" layer of the UIView and can't be used as a delegate for another layer.) The solution is to use another object as a delegate which can be a "private" class just used to implement the drawLayer: inContext: method.

Thorsten
  • 12,921
  • 17
  • 60
  • 79