简体   繁体   English

如何在 iOS 13 中使用 UINavigationBarAppearance

[英]How to use UINavigationBarAppearance in iOS 13

How do you use this new object to customize the navigation bar in iOS 13?如何使用这个新的 object 自定义 iOS 13 中的导航栏? I tried the following code in Objective-C but it's not working correctly.我在 Objective-C 中尝试了以下代码,但它无法正常工作。 It only shows my title text attributes while a view controller is being pushed or popped on to the navigation stack.当视图 controller 被推送或弹出到导航堆栈时,它只显示我的标题文本属性。

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

Here is the documentation for this object.这是此 object 的文档。 https://developer.apple.com/documentation/uikit/uinavigationbarappearance?language=objc https://developer.apple.com/documentation/uikit/uinavigationbarappearance?language=objc

It isn't enough to just create an instance of UINavigationBarAppearance .仅仅创建UINavigationBarAppearance的实例是不够的。 You have to actually set it on a UINavigationBar instance (or its appearance proxy).您必须在UINavigationBar实例(或其外观代理)上实际设置它。

// 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.

If you want this same customization on all nav bars in the app, apply it to the UINavigationBar.appearance proxy.如果您想在应用程序中的所有导航栏上进行相同的自定义,请将其应用于UINavigationBar.appearance代理。

UINavigationBar.appearance.standardAppearance = appearance;

For me, even though I correctly set the appearance to the current UINavigationBar, it was still not working.对我来说,即使我正确地将外观设置为当前的 UINavigationBar,它仍然无法正常工作。

I found out that you need to call navigationBar?.setNeedsLayout() , if you set an updated appearance on a UINavigationBar that is already being displayed.我发现如果您在已显示的 UINavigationBar 上设置了更新的外观,您需要调用navigationBar?.setNeedsLayout()

in iOS13 you need to set the title color on the UINavigationBarAppearance object like here (Objective C version):在 iOS13 中,您需要像这里一样在 UINavigationBarAppearance object 上设置标题颜色(目标 C 版本):

UINavigationBarAppearance *appearance = [[UINavigationBarAppearance alloc] init];
appearance.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]};
self.navigationController.navigationBar.standardAppearance = appearance;
self.navigationController.navigationBar.scrollEdgeAppearance = appearance;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM