iOS 13中如何使用UINavigationBarAppearance

6

如何使用这个新对象来定制iOS 13中的导航栏?我尝试在Objective-C中使用以下代码,但它没有正确地工作。仅当一个视图控制器被推送或弹出到导航堆栈时,它才显示我的标题文本属性。

UINavigationBarAppearance *appearance = [UINavigationBarAppearance new];
appearance.titleTextAttributes = @{NSFontAttributeName: font};

这个对象的文档在这里。 https://developer.apple.com/documentation/uikit/uinavigationbarappearance?language=objc

展示如何将 appearance 变量应用于导航栏。 - rmaddy
这就是我困惑的地方。文档只是指示创建一个对象并设置属性。 - Berry Blue
3个回答

17

仅仅创建一个 UINavigationBarAppearance 实例是不够的,你必须将其实际设置在一个 UINavigationBar 实例上(或者它的 appearance proxy 上)。

// Setup the nav bar appearance
UINavigationBarAppearance *appearance = [UINavigationBarAppearance new];
appearance.titleTextAttributes = @{NSFontAttributeName: font};

// Apply it to a specific nav bar
someNavBarInstance.standardAppearance = appearance;
// There are also the compactAppearance and scrollEdgeAppearance properties that can be set as needed.
如果你想在应用程序的所有导航栏中进行相同的自定义,请将其应用于UINavigationBar.appearance代理。
UINavigationBar.appearance.standardAppearance = appearance;

好的,谢谢。在 Objective-C 中我该如何使用 UINavigationBar.appearance - Berry Blue
请查看我的更新回答。将您的变量命名为“appearance”会使代码有点混乱。 - rmaddy
好的,看起来可以工作!唯一的问题是在推入和弹出视图时,它没有保持我的字体大小。外观中不再支持字体大小吗? - Berry Blue
也许您对不同的导航栏有不同的设置。请注意,如果您希望整个应用程序使用相同的设置并且使用 UINavigationBar.appearance 代理,则请确保在任何代码运行或创建任何 UI 之前在应用程序委托中设置它。外观代理仅适用于在其设置后创建的 UI 元素。 - rmaddy
谢谢,是的,我正在做这个,但它没有起作用。至少感谢您帮助我到这一步。 - Berry Blue
显示剩余3条评论

2

对我来说,即使我正确地将外观设置为当前的UINavigationBar,它仍然无法正常工作。

我发现,如果您在已经显示的UINavigationBar上设置了更新的外观,则需要调用navigationBar?.setNeedsLayout()


-1
在iOS13上,您需要像这样在UINavigationBarAppearance对象上设置标题颜色(Objective C版本):
UINavigationBarAppearance *appearance = [[UINavigationBarAppearance alloc] init];
appearance.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]};
self.navigationController.navigationBar.standardAppearance = appearance;
self.navigationController.navigationBar.scrollEdgeAppearance = appearance;

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