iOS15下有限图库选择器导航栏颜色设置异常如何解决
iOS15 有限图库选择器导航栏颜色设置异常解决
问题描述
我尝试设置有限图库选择器的导航栏颜色,在AppDelegate.application:didFinishLaunchingWithOptions:方法中添加了如下代码:
if (@available(iOS 13, *)) { UINavigationBarAppearance *navigationBarAppearance = [UINavigationBarAppearance new]; navigationBarAppearance.backgroundColor = UIColor.yellowColor; [UINavigationBar appearance].standardAppearance = navigationBarAppearance; [UINavigationBar appearance].scrollEdgeAppearance = navigationBarAppearance; } [UINavigationBar appearance].barTintColor = UIColor.greenColor; [UINavigationBar appearance].backgroundColor = UIColor.redColor;
上述代码在iOS14上运行符合预期,导航栏显示为绿色:
但在iOS15上运行时,导航栏显示为淡红色:
补充说明
最小可复现示例:新建单视图控制器iOS项目,在info.plist中添加NSPhotoLibraryUsageDescription权限声明,核心代码如下:
import UIKit import Photos import PhotosUI class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // 视图加载完成后的额外配置 PHPhotoLibrary.requestAuthorization(for: .readWrite, handler: { _ in}) PHPhotoLibrary.shared().presentLimitedLibraryPicker(from: self) } }
AppDelegate.swift代码:
import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 应用启动后自定义配置入口 if #available(iOS 13, *) { let navigationBarAppearance = UINavigationBarAppearance() navigationBarAppearance.backgroundColor = UIColor.yellow UINavigationBar.appearance().standardAppearance = navigationBarAppearance UINavigationBar.appearance().scrollEdgeAppearance = navigationBarAppearance } UINavigationBar.appearance().barTintColor = UIColor.green UINavigationBar.appearance().backgroundColor = UIColor.red return true } // MARK: UISceneSession 生命周期 func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // 新建场景会话时调用,用于选择创建场景的配置 return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } }
失效原因
iOS15开始,UINavigationBar默认开启半透明效果,全局设置的
barTintColor、UINavigationBarAppearance.backgroundColor会被系统自带的有限图库选择器的导航栏默认样式叠加半透明遮罩,导致最终显示的颜色与预期不符。
解决方案
通过生成1px纯色图片作为导航栏背景图,强制覆盖系统默认渲染逻辑,兼容全iOS版本:
Objective-C 版本
UIGraphicsImageRenderer * imageRenderer = [[UIGraphicsImageRenderer alloc]initWithSize:CGSizeMake(1, 1)]; UIImage *image = [imageRenderer imageWithActions:^(UIGraphicsImageRendererContext *context){ // 替换为你需要的导航栏颜色即可 [UIColor.greenColor setFill]; [context fillRect:CGRectMake(0, 0, 1, 1)]; }]; [[UINavigationBar appearance] setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
Swift 版本
let imageRenderer = UIGraphicsImageRenderer(size: CGSize(width: 1, height: 1)) let image = imageRenderer.image { context in // 替换为你需要的导航栏颜色即可 UIColor.green.setFill() context.fill(CGRect(x: 0, y: 0, width: 1, height: 1)) } UINavigationBar.appearance().setBackgroundImage(image, for: .default)
内容的提问来源于stack exchange,提问作者BenJacob
相关产品推荐
相关产品推荐

