0

我试图使用以下代码为导航栏设置渐变,但应用程序在最后一行崩溃并出现 EXC_BAD_ACCESS 错误。

UIColor* topColor = [UIColor colorWithRed:245.0/255 green:245.0/255 blue:245.0/255 alpha:1.0];
UIColor* bottomColor = [UIColor colorWithRed:200.0/255 green:200.0/255 blue:200.0/255 alpha:1.0];
CAGradientLayer* navBarGradientLayer = [CAGradientLayer layer];
[navBarGradientLayer setFrame:CGRectMake(0, 0, self.navigationController.navigationBar.bounds.size.width, self.navigationController.navigationBar.bounds.size.height)];
NSArray* gradientColors = @[topColor, bottomColor];
navBarGradientLayer.colors = gradientColors;
[self.navigationController.navigationBar.layer insertSublayer:navBarGradientLayer atIndex:0];

我在这里做错了什么?

4

2 回答 2

0

试试这个,它对我有用

UINavigationBar *navigationBar= [[self.navigationController.navigationBar subviews]objectAtIndex:0];


UIView* gradientViewnavigationBar = [[UIView alloc] initWithFrame:CGRectMake(0,0,navigationBar.frame.size.width,navigationBar.frame.size.height)];


CAGradientLayer * gradientLayernavigationBar = [[[CAGradientLayer alloc] init] autorelease];

gradientLayernavigationBar.frame = gradientViewnavigationBar.bounds;
gradientLayernavigationBar.colors = [NSArray arrayWithObjects:(id)[startColornavigationBar CGColor], (id)[endColornavigationBar CGColor], nil];

gradientLayernavigationBar.opacity=1.0;

//设置渐变角度

  [CustomNavBar setAngleForGradients:gradientLayernavigationBar angle:[[nav_header_Element attributeForName:@"angle"]stringValue]];

[gradientViewnavigationBar.layer insertSublayer:gradientLayernavigationBar atIndex:0];
[navigationBar insertSubview:gradientViewnavigationBar atIndex:0];
[gradientViewnavigationBar release];
于 2012-12-15T15:20:39.023 回答
0
// get navigation bar objc
UINavigationBar *navigationBar= [[self.navigationController.navigationBar subviews]objectAtIndex:0];

//create uiview 
        UIView* gradientViewnavigationBar = [[UIView alloc] initWithFrame:CGRectMake(0,0,navigationBar.frame.size.width,navigationBar.frame.size.height)];

// create layer of gradient color 
CAGradientLayer * gradientLayernavigationBar = [[CAGradientLayer alloc] init];

gradientLayernavigationBar.frame = gradientViewnavigationBar.bounds;
gradientLayernavigationBar.colors = [NSArray arrayWithObjects:(id)[[UIColor redColor] CGColor], (id)[[UIColor  blackColor] CGColor], nil];

gradientLayernavigationBar.opacity=1.0;

// add layer on view 
// then add view on navigation bar   
[gradientViewnavigationBar.layer insertSublayer:gradientLayernavigationBar atIndex:0];
[navigationBar insertSubview:gradientViewnavigationBar atIndex:0];

i hope it will help you!

于 2015-06-17T07:13:46.833 回答