如何在 iOS 13 中全局设置栏按钮项背景图像

mat*_*att 4 uibarbuttonitem ios ios13

iOS 13 有一组全新的类用于配置导航栏和栏按钮项:

  • UIBar外观
  • UINavigationBar外观
  • UIBarButtonItemAppearance
  • UIBarButtonItemStateAppearance

我如何使用这些来为栏按钮项目提供全局外观?假设我希望所有条形按钮项目都有一个共同的背景图像。我曾经说过:

UIBarButtonItem.appearance().setBackgroundImage(im, for:.normal, barMetrics:.default)
Run Code Online (Sandbox Code Playgroud)

这似乎正是这些新类所取代的。那么现在正确的方法是什么?

mat*_*att 6

它很冗长,但在某些方面它更清晰。您可以配置导航栏外观并standardAppearance通过代理将其分配给导航栏:

    let app = UIBarButtonItemAppearance()
    app.normal.backgroundImage = im
    let navbarapp = UINavigationBarAppearance()
    navbarapp.configureWithOpaqueBackground()
    navbarapp.buttonAppearance = app
    UINavigationBar.appearance().standardAppearance = navbarapp
Run Code Online (Sandbox Code Playgroud)

唯一的问题是它为后退按钮项目分配了相同的背景图像。因此,如果不需要,您必须进行防御性编码,为后退按钮项目分配一个空的(非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
Run Code Online (Sandbox Code Playgroud)