[英]How to set bar button item background image globally in iOS 13
iOS 13 has a whole new set of classes for configuring navigation bars and bar button items: iOS 13 有一组全新的类用于配置导航栏和栏按钮项:
How do I use these to give bar button items a global appearance?我如何使用这些来为栏按钮项目提供全局外观? Let's say I want all bar button items to have a common background image.
假设我希望所有条形按钮项目都有一个共同的背景图像。 I used to say:
我曾经说过:
UIBarButtonItem.appearance().setBackgroundImage(im, for:.normal, barMetrics:.default)
This seems to be just what is superseded by these new classes.这似乎正是这些新类所取代的。 So what's the right way now?
那么现在正确的方法是什么?
It's verbose, but in some ways it's clearer.它很冗长,但在某些方面它更清晰。 You can configure a navigation bar appearance and assign it to the navigation bar's
standardAppearance
through the proxy:您可以配置导航栏外观,并通过代理将其分配给导航栏的
standardAppearance
:
let app = UIBarButtonItemAppearance()
app.normal.backgroundImage = im
let navbarapp = UINavigationBarAppearance()
navbarapp.configureWithOpaqueBackground()
navbarapp.buttonAppearance = app
UINavigationBar.appearance().standardAppearance = navbarapp
The only problem with that is that it assigns the same background image to back button items.唯一的问题是它为后退按钮项目分配了相同的背景图像。 So if that's not desired, you have to code defensively, assigning back button items an empty (not
nil
) image:因此,如果这不是您想要的,您必须进行防御性编码,为后退按钮项目分配一个空的(不是
nil
)图像:
let app = UIBarButtonItemAppearance()
app.normal.backgroundImage = im
let navbarapp = UINavigationBarAppearance()
navbarapp.configureWithOpaqueBackground()
navbarapp.buttonAppearance = app
let back = UIBarButtonItemAppearance()
back.normal.backgroundImage = UIImage() // prevent back button item
navbarapp.backButtonAppearance = back
UINavigationBar.appearance().standardAppearance = navbarapp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.