当前位置:
首页
文章
移动端
详情

[iOS] iOS15+设置导航背景色不起作用问题

在自定义设置导航背景色时,使用下面的方法,在iOS15+系统上不起作用:

UINavigationBar *appearance = [UINavigationBar appearance];
//        [appearance confi];
        [appearance setBarTintColor:[UIColor whiteColor]];
        [appearance setTintColor: [UIColor whiteColor]];
        appearance.translucent = NO;
        NSMutableDictionary *textAttribute = [NSMutableDictionary dictionary];
        textAttribute[NSForegroundColorAttributeName] = MPColorBlue;//标题颜色
        textAttribute[NSFontAttributeName] = [UIFont boldSystemFontOfSize:18];//标题大小
        [appearance setTitleTextAttributes:textAttribute];
        
        UIColor *color = MPMainColor;
        UIImage *backGroundImage = [UIImage imageWithColor:color];
        backGroundImage = [backGroundImage resizableImageWithCapInsets:UIEdgeInsetsZero resizingMode:UIImageResizingModeStretch];
        [appearance setBackgroundImage:backGroundImage forBarMetrics:UIBarMetricsDefault];
//        appearance.backgroundColor = color;
    
        //去除底部黑线
        [appearance setShadowImage:[UIImage new]];

但是,如你的页面有scrollView,例如table、webView这些,滑动的时候,导航颜色会变为你设置的颜色,但是一旦滑动到顶部,导航又会不正常,变成黑色;

查了资料,说在iOS15+使用下面的方法:

UINavigationBarAppearance *appearance = [[UINavigationBarAppearance alloc] init];
    
    [appearance configureWithOpaqueBackground];
    NSMutableDictionary *textAttribute = [NSMutableDictionary dictionary];
    textAttribute[NSForegroundColorAttributeName] = MPColorBlue;//标题颜色
    textAttribute[NSFontAttributeName] = [UIFont boldSystemFontOfSize:18];//标题大小
    [appearance setTitleTextAttributes:textAttribute];
    
    //去除底部黑线
    [appearance setShadowImage:[UIImage new]];
    
    UIColor *color = MPMainColor;
     appearance.backgroundColor = color;
    
    self.navigationBar.standardAppearance = appearance;

该方法表现和上面一致;

最终在一个文章里看到这个属性:

self.navigationBar.scrollEdgeAppearance

需要把这个也设置了才会表现正常,最终完整的设置如下:

UINavigationBarAppearance *appearance = [[UINavigationBarAppearance alloc] init];
    
    [appearance configureWithOpaqueBackground];
    NSMutableDictionary *textAttribute = [NSMutableDictionary dictionary];
    textAttribute[NSForegroundColorAttributeName] = MPColorBlue;//标题颜色
    textAttribute[NSFontAttributeName] = [UIFont boldSystemFontOfSize:18];//标题大小
    [appearance setTitleTextAttributes:textAttribute];
    
    //去除底部黑线
    [appearance setShadowImage:[UIImage new]];
    
    UIColor *color = MPMainColor;
    appearance.backgroundColor = color;
    
    self.navigationBar.standardAppearance = appearance;
    self.navigationBar.scrollEdgeAppearance = appearance;

我这里设置的 backgroundColor,你也可以设置BackgroundImage

免责申明:本站发布的内容(图片、视频和文字)以转载和分享为主,文章观点不代表本站立场,如涉及侵权请联系站长邮箱:xbc-online@qq.com进行反馈,一经查实,将立刻删除涉嫌侵权内容。