iOS15导航栏适配,亲测有效[OC+Swift版本]

938 阅读1分钟
前言

在 iOS 15 之后发现常规设置 navigationBar 与 tabBar 的背景色后仍无效,具体需要配置如下 UINavigationBarAppearance 和 UITabBarAppearance 即可。

OC版本
if (@available(iOS 15.0, *)) {
        UINavigationBarAppearance * appearance = [[UINavigationBarAppearance alloc] init];
        appearance.backgroundColor = UIColor.ColorFFFFFF;
        appearance.backgroundEffect = nil;
        
        // 去除导航栏阴影(如果不设置clear,导航栏底下会有一条阴影线)
        appearance.shadowColor = [UIColor clearColor];
        // 字体颜色、尺寸等
        appearance.titleTextAttributes = @{NSForegroundColorAttributeName: UIColor.Color182D44};
        // 带scroll滑动的页面
        self.navigationController.navigationBar.scrollEdgeAppearance = appearance;
        // 常规页面
        self.navigationController.navigationBar.standardAppearance = appearance;
    } else {
        // 常规配置方式
        self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: UIColor.Color182D44};
        self.navigationController.navigationBar.barTintColor = UIColor.ColorFFFFFF;
    }
Swift版本
if #available(iOS 15.0, *) {

   let appearance = UINavigationBarAppearance()

   appearance.backgroundColor = .blue

   appearance.backgroundEffect = nil

   //导航栏标题颜色

   let attrDic = [NSAttributedString.Key.foregroundColor:UIColor.red,

                                                             NSAttributedString.Key.font:UIFont.systemFont(ofSize: 18.0)]

   //设置字体颜色大小

   appearance.titleTextAttributes = attrDic;

   //设置图片

   //appearance.backgroundImage = UIImage(named: "xxxxx")

   self.navigationController?.navigationBar.standardAppearance = appearance

   self.navigationController?.navigationBar.scrollEdgeAppearance = appearance

}else{

   self.navigationController?.navigationBar.barTintColor = .blue

   let dict:NSDictionary = [NSAttributedString.Key.foregroundColor: UIColor.red,NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 18)]

   //标题颜色

   self.navigationController?.navigationBar.titleTextAttributes = dict as? [NSAttributedString.Key : AnyObject]

}