iOS开发:如何修改CNContactPickerViewController的导航栏颜色?
我太懂这个坑了!直接用全局的UINavigationBar.appearance()改CNContactPickerViewController的导航栏样式基本没用,因为系统自带的联系人选择器内部的导航栏是独立管理的,全局样式会被它的默认设置覆盖。给你几个靠谱的解决办法:
解决方案1:精准定位目标导航栏(推荐)
用UIAppearance的容器限定方法,只对CNContactPickerViewController内部的导航栏应用样式,不会影响其他页面的导航栏:
// 先设置仅针对CNContactPickerViewController的导航栏样式 UINavigationBar.appearance(whenContainedInInstancesOf: [CNContactPickerViewController.self]).isTranslucent = false UINavigationBar.appearance(whenContainedInInstancesOf: [CNContactPickerViewController.self]).barTintColor = .white // 要是还想改标题颜色,也可以加上 UINavigationBar.appearance(whenContainedInInstancesOf: [CNContactPickerViewController.self]).titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black] // 再初始化并present联系人选择器 let contactPicker = CNContactPickerViewController() contactPicker.delegate = self contactPicker.modalPresentationStyle = .fullScreen contactPicker.displayedPropertyKeys = [CNContactPhoneNumbersKey, CNContactEmailAddressesKey] contactPicker.predicateForEnablingContact = NSPredicate(format: "emailAddresses.@count > 0 || phoneNumbers.@count > 0") present(contactPicker, animated: true)
这个方法是苹果官方推荐的针对特定容器内控件设置样式的方式,稳定性最高。
解决方案2:present后延迟设置(应急用)
如果方案1暂时不生效(比如某些iOS版本的兼容性问题),可以在present完成后直接获取导航栏设置,但可能会有动画闪屏的问题:
let contactPicker = CNContactPickerViewController() contactPicker.delegate = self contactPicker.modalPresentationStyle = .fullScreen contactPicker.displayedPropertyKeys = [CNContactPhoneNumbersKey, CNContactEmailAddressesKey] contactPicker.predicateForEnablingContact = NSPredicate(format: "emailAddresses.@count > 0 || phoneNumbers.@count > 0") present(contactPicker, animated: true) { // present完成后再修改导航栏样式 contactPicker.navigationController?.navigationBar.isTranslucent = false contactPicker.navigationController?.navigationBar.barTintColor = .white }
额外:修改搜索栏样式(如果你需要的话)
看你代码里注释了搜索相关的设置,要是想改联系人选择器里的搜索栏样式,同样可以用容器限定:
UISearchBar.appearance(whenContainedInInstancesOf: [CNContactPickerViewController.self]).barTintColor = .white // 搜索输入框的背景色 UISearchBar.appearance(whenContainedInInstancesOf: [CNContactPickerViewController.self]).searchTextField.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
内容的提问来源于stack exchange,提问作者Dhiren
相关产品推荐
相关产品推荐

