在iOS 13中将UIImagePickerController导航栏设置为不透明

5

我正在使用 UIImagePickerController 呈现一个图片选择器。我的代码非常简单:

private lazy var imagePicker: UIImagePickerController = {
    let picker = UIImagePickerController()
    picker.navigationBar.isTranslucent = false
    return picker
}()

func presentPicker() {
    imagePicker.sourceType = .photoLibrary
    imagePicker.modalPresentationStyle = .fullScreen        
    present(self.imagePicker, animated: true, completion: nil)
}

我在选择器控制器中设置 picker.navigationBar.isTranslucent = false 以获得不透明的导航栏。不幸的是,在iOS 13上,此方法无效,导航栏和状态栏仍然是透明的。

部分解决方案:

private func setOpaqueNavigationiOS13() {
    UINavigationBar.appearance().backgroundColor = .white
}

private func resetNavigationiOS13() {
    UINavigationBar.appearance().backgroundColor = .clear
}

我调用上述功能使导航栏变为不透明,并在取消选择器时重置它。这使得导航栏不透明,但状态栏仍然透明。我可以实现一个技巧来使状态栏也不透明,但我觉得应该有更简单的解决方案。 < p > 编辑: 我还尝试使用新的UINavigationBarAppearance设置导航栏的外观:

if #available(iOS 13.0, *) {
    let appearance = UINavigationBarAppearance()
    appearance.configureWithOpaqueBackground()
    appearance.backgroundColor = .white
    UINavigationBar.appearance().standardAppearance = appearance
    UINavigationBar.appearance().compactAppearance = appearance
    UINavigationBar.appearance().scrollEdgeAppearance = appearance
}

或者:

if #available(iOS 13.0, *) {
    let appearance = UINavigationBarAppearance()
    appearance.configureWithOpaqueBackground()
    appearance.backgroundColor = .white
    imagePicker.navigationBar.standardAppearance = appearance
    imagePicker.navigationBar.compactAppearance = appearance
    imagePicker.navigationBar.scrollEdgeAppearance = appearance
}

有人提出了解决方法吗?谢谢。

这会使导航栏不透明,但状态栏是透明的。没错,你绝对不应该像那样设置导航栏的背景颜色。在iOS 13中,使用新的UIBarAppearance架构,并保持isTranslucent属性不变。 - matt
2个回答

0
我在这里发布我的解决方案,以便对其他人有所帮助。 虽然matt的答案完全正确,但它仅适用于通过UINavigationBarAppearance完成所有导航栏设置的情况。但在我的情况下,这并没有帮助,因为我已经在AppDelegate中完成了此操作:
// Make navigation bar transparent throughout whole app
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)

由于我的应用程序展示了许多导航栏样式,我需要一个快速的解决方案来满足iOS 13的更改,所以我只是这样做:

// Set nav bar to opaque 
if #available(iOS 13.0, *) {
    UINavigationBar.appearance().setBackgroundImage(nil, for: .default)
}

只是不要忘记在需要时将其恢复为透明。


-1
在iOS 13中,自定义导航栏外观的正确方法是使用UIBarAppearance架构(导航栏的 standardAppearance 等)。 您可以将其直接应用于导航栏或使用UINavigationBar外观代理。

我也尝试过这种方法,但没有成功。我会在我的问题中更新代码。谢谢。 - Vasil Garov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接