使用CAGradientLayer自定义导航栏颜色

时间:2012-10-31 05:43:44

标签: cocoa-touch uikit

我尝试使用以下代码为导航栏设置渐变,但应用程序在最后一行崩溃并出现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];

我在这里做错了什么?

2 个答案:

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

答案 1 :(得分:0)

public static <T extends RealmObject> void executeInsertInto(final Context context, final T passedObject){
    Realm realm = Realm.getInstance(context);
    realm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            T itemToWrite = realm.copyToRealm(passedObject);
        }
    });
    realm.close();
}

我希望它会对你有所帮助!