iOS14.8下如何修改UIImagePickerController搜索栏的背景颜色
iOS 14.8 UIImagePickerController搜索栏背景异常修复方案
在iOS 14.8系统中调用系统UIImagePickerController时,控件自带的搜索栏默认背景为透明,会和后方视图内容重叠导致显示异常,可通过以下方案修复:
相关参考截图:

方案1:弹出UIImagePickerController时动态修改搜索栏背景
该方案不会影响全局其他搜索栏样式,适配性更高:
Objective-C 代码示例
UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; // 弹出后延迟遍历视图层级查找搜索栏 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self findSearchBarInView:picker.view]; }); [self presentViewController:picker animated:YES completion:nil]; // 递归遍历视图查找UISearchBar - (void)findSearchBarInView:(UIView *)view { for (UIView *subview in view.subviews) { if ([subview isKindOfClass:[UISearchBar class]]) { UISearchBar *searchBar = (UISearchBar *)subview; // 替换为你需要的背景色 searchBar.backgroundColor = [UIColor whiteColor]; // 可选:设置纯色背景图片彻底覆盖透明效果 [searchBar setBackgroundImage:[UIImage new] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault]; return; } [self findSearchBarInView:subview]; } }
Swift 代码示例
let picker = UIImagePickerController() picker.sourceType = .photoLibrary present(picker, animated: true) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.findSearchBar(in: picker.view) } } func findSearchBar(in view: UIView) { for subview in view.subviews { if let searchBar = subview as? UISearchBar { // 替换为你需要的背景色 searchBar.backgroundColor = .white // 可选:设置纯色背景图片彻底覆盖透明效果 searchBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default) return } findSearchBar(in: subview) } }
方案2:全局修改UISearchBar外观
如果App内所有搜索栏需要统一背景样式,可直接通过外观协议设置,代码更简洁:
Objective-C 代码示例
[[UISearchBar appearance] setBackgroundColor:[UIColor whiteColor]]; [[UISearchBar appearance] setBackgroundImage:[UIImage new] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
Swift 代码示例
UISearchBar.appearance().backgroundColor = .white UISearchBar.appearance().setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
注意:如果设置后仍存在透明效果,可额外修改搜索栏的
searchTextField子视图的背景色,彻底覆盖系统默认透明属性。
内容的提问来源于stack exchange,提问作者Zas
相关产品推荐
相关产品推荐

