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

时间:2011-05-20 16:11:12

标签: iphone uibutton calayer exc-bad-access gradient

嘿,人们, 我尝试为UIButtonTypeRoundedRect添加一个漂亮的渐变。

中实现了以下代码
viewWillAppear:(BOOL)animated   

我的视图控制器的功能。

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];

代码运行正常,直到应用程序尝试显示视图 - 它以 EXC_BAD_ACCESS 崩溃。但如果我注释掉

[downButtonLayer addSublayer:hintergrundButtonLayer];   

命令,然后一切都很好。

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

有人看到我的问题吗?

1 个答案:

答案 0 :(得分: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]];

如果您在崩溃中读取顶部堆栈帧(在调试器下运行时),则表明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:] ()