iphone:将CALayer作为子层添加到UIButton的层会导致EXC_BAD_ACCESS

dac*_*dac 4 iphone gradient exc-bad-access uibutton calayer

嘿人,我尝试为UIButtonTypeRoundedRect添加一个漂亮的渐变.以下代码在.中实现

viewWillAppear:(BOOL)animated   
Run Code Online (Sandbox Code Playgroud)

我的视图控制器的功能.

UIButton *tempButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
tempButton.frame = CGRectMake(left, top, 80.0f, 80.0f); 

CAGradientLayer * hintergrundButtonLayer = [[CAGradientLayer alloc] init];
[hintergrundButtonLayer setBounds:tempButton.bounds];
[hintergrundButtonLayer setColors:[NSArray arrayWithObjects: 
                   [UIColor colorWithRed:0.2 green:0.3 blue:0.4 alpha:1.0],
                   [UIColor colorWithRed:0.4 green:0.5 blue:0.6 alpha:1.0], 
                   nil]];

[hintergrundButtonLayer setPosition: 
             CGPointMake([tempButton bounds].size.width/2, 
                         [tempButton bounds].size.height/2)];

[hintergrundButtonLayer setLocations:
                       [NSArray arrayWithObjects:
                              [NSNumber numberWithFloat:0.0], 
                              [NSNumber numberWithFloat:1.0], 
                              nil]];

//      hintergrundButtonLayer.zPosition = -10;
//      hintergrundButtonLayer.frame = [tempButton bounds];


[tempButton addTarget:self action:@selector(switchVendorOnOff:) forControlEvents:UIControlEventTouchUpInside];


CALayer * downButtonLayer = [tempButton layer];
[downButtonLayer setMasksToBounds:YES];
[downButtonLayer setCornerRadius:10.0];
[downButtonLayer setBorderWidth:1.2];
[downButtonLayer setBorderColor:[[UIColor blackColor] CGColor]];


[downButtonLayer addSublayer:hintergrundButtonLayer];

[hintergrundButtonLayer release];
hintergrundButtonLayer = nil;

[self.view addSubview:tempButton];
Run Code Online (Sandbox Code Playgroud)

代码运行正常,直到应用程序尝试显示视图 - 它与EXC_BAD_ACCESS崩溃.但如果我发表评论

[downButtonLayer addSublayer:hintergrundButtonLayer];   
Run Code Online (Sandbox Code Playgroud)

命令,然后一切都很好.

调试器没有告诉我任何泄漏信息.分配模板也没什么奇怪的.除了EXC_BAD_ACCESS消息之外,没有其他任何内容打印到控制台."构建和分析"显示没有错误.

有谁看到我的问题?

dic*_*ciu 8

setColors采用CGColors,而不是UIColors.

[hintergrundButtonLayer setColors:[NSArray arrayWithObjects: 
    [[UIColor colorWithRed:0.2 green:0.3 blue:0.4 alpha:1.0] CGColor],
    [[UIColor colorWithRed:0.4 green:0.5 blue:0.6 alpha:1.0] CGColor], 
    nil]];
Run Code Online (Sandbox Code Playgroud)

如果您在崩溃中读取顶部堆栈帧(在调试器下运行时),则表明CGColors存在问题:

(gdb) bt
#0  0x00bd407c in CGColorSpaceGetMD5Digest ()
#1  0x00b4f8b2 in CGColorTransformConvertColorFloatComponents ()
#2  0x00b4fea2 in CGColorTransformConvertColorComponents ()
#3  0x00cb0d62 in CA_CGColorGetRGBComponents ()
#4  0x00d509aa in -[CAGradientLayer _copyRenderLayer:layerFlags:commitFlags:] ()
Run Code Online (Sandbox Code Playgroud)