如何更改iOS上的UISearchBar组件的背景颜色

我知道如何删除/更改search字段周围的UISearchBar背景颜色:

 [[self.searchBar.subviews objectAtIndex:0] removeFromSuperview]; self.searchBar.backgroundColor = [UIColor grayColor]; 

实现了UISearchBar的自定义

但不知道如何做到这一点:

所需的UISearchBar定制

这需要与iOS 4.3+兼容。

使用此代码来更改searchBar的UITextField backgroundImage:

 UITextField *searchField; NSUInteger numViews = [searchBar.subviews count]; for (int i = 0; i < numViews; i++) { if ([[searchBar.subviews objectAtIndex:i] isKindOfClass:[UITextField class]]) { //conform? searchField = [searchBar.subviews objectAtIndex:i]; } } if (searchField) { searchField.textColor = [UIColor whiteColor]; [searchField setBackground: [UIImage imageNamed:@"yourImage"]]; //set your gray background image here [searchField setBorderStyle:UITextBorderStyleNone]; } 

使用下面的代码来更改UISearchBarIcon

  UIImageView *searchIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yourSearchBarIconImage"]]; searchIcon.frame = CGRectMake(10, 10, 24, 24); [searchBar addSubview:searchIcon]; [searchIcon release]; 

此外,要更改searchBar图标,可以在UISearchBar (可从iOS 5+获得 )上使用以下内置方法:

 - (void)setImage:(UIImage *)iconImage forSearchBarIcon:(UISearchBarIcon)icon state:(UIControlState)state 

在这里你可以设置4种types的UISearchBarIcon即:

  1. UISearchBarIconBookmark
  2. UISearchBarIconClear
  3. UISearchBarIconResultsList
  4. UISearchBarIconSearch

我希望这可以帮助你…

只需自定义文本字段本身。

我只是这样做,它适用于我(iOS 7)。

 UITextField *txfSearchField = [_searchBar valueForKey:@"_searchField"]; txfSearchField.backgroundColor = [UIColor redColor]; 

这样你不需要创build一个图像,大小等等…

不涉及任何私人API的解决scheme! 🙂

目前( 可能从iOS 5开始 ),你可以这样做,只需一种颜色的情况下,就可以这样做:

 [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundColor:[UIColor redColor]]; 

但请记住,由于它的外观基础上的变化将是全球性的应用程序(这可能是一个优势或解决scheme的缺点)。

对于Swift你可以使用(它将适用于iOS 9及以上):

 if #available(iOS 9.0, *) { UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).backgroundColor = UIColor.darkGrayColor() } 

如果您的项目支持iOS 9或更高版本,则不需要#available

如果你需要支持iOS的早期版本,并想使用Swift,请看看这个问题。

根据UISearchBar文档 :

你应该使用iOS 5.0+的这个function。

 - (void)setSearchFieldBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state 

用法示例:

 [mySearchBar setSearchFieldBackgroundImage:myImage forState:UIControlStateNormal]; 

不幸的是,在iOS 4中,您需要恢复不太复杂的方法。 查看其他答案。

正如Accatyyc所说的iOS5 +使用setSearchFieldBackgroundImage,但您需要创build一个graphics,或执行以下操作:

 CGSize size = CGSizeMake(30, 30); // create context with transparent background UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale); // Add a clip before drawing anything, in the shape of an rounded rect [[UIBezierPath bezierPathWithRoundedRect:CGRectMake(0,0,30,30) cornerRadius:5.0] addClip]; [[UIColor grayColor] setFill]; UIRectFill(CGRectMake(0, 0, size.width, size.height)); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); [self.searchBar setSearchFieldBackgroundImage:image forState:UIControlStateNormal]; 

Swift 3,xcode 8.2.1

UISearchBar自定义示例

完整的样品

UISearchBar扩展

 extension UISearchBar { private func getViewElement<T>(type: T.Type) -> T? { let svs = subviews.flatMap { $0.subviews } guard let element = (svs.filter { $0 is T }).first as? T else { return nil } return element } func setTextFieldColor(color: UIColor) { if let textField = getViewElement(type: UITextField.self) { switch searchBarStyle { case .minimal: textField.layer.backgroundColor = color.cgColor textField.layer.cornerRadius = 6 case .prominent, .default: textField.backgroundColor = color } } } } 

用法

 let searchBar = UISearchBar(frame: CGRect(x: 0, y: 20, width: UIScreen.main.bounds.width, height: 44)) //searchBar.searchBarStyle = .prominent view.addSubview(searchBar) searchBar.placeholder = "placeholder" searchBar.setTextFieldColor(color: UIColor.green.withAlphaComponent(0.3)) 

结果1

  searchBar.searchBarStyle = .prominent // or default 

在这里输入图像描述

结果2

  searchBar.searchBarStyle = .minimal 

在这里输入图像描述

我发现这是使用UISearchBarStyle.Minimal在Swift 2.2和iOS 8+中自定义各种search栏属性外观的最佳方法

 searchBar = UISearchBar(frame: CGRectZero) searchBar.tintColor = UIColor.whiteColor() // color of bar button items searchBar.barTintColor = UIColor.fadedBlueColor() // color of text field background searchBar.backgroundColor = UIColor.clearColor() // color of box surrounding text field searchBar.searchBarStyle = UISearchBarStyle.Minimal // Edit search field properties if let searchField = searchBar.valueForKey("_searchField") as? UITextField { if searchField.respondsToSelector(Selector("setAttributedPlaceholder:")) { let placeholder = "Search" let attributedString = NSMutableAttributedString(string: placeholder) let range = NSRange(location: 0, length: placeholder.characters.count) let color = UIColor(white: 1.0, alpha: 0.7) attributedString.addAttribute(NSForegroundColorAttributeName, value: color, range: range) attributedString.addAttribute(NSFontAttributeName, value: UIFont(name: "AvenirNext-Medium", size: 15)!, range: range) searchField.attributedPlaceholder = attributedString searchField.clearButtonMode = UITextFieldViewMode.WhileEditing searchField.textColor = .whiteColor() } } // Set Search Icon let searchIcon = UIImage(named: "search-bar-icon") searchBar.setImage(searchIcon, forSearchBarIcon: .Search, state: .Normal) // Set Clear Icon let clearIcon = UIImage(named: "clear-icon") searchBar.setImage(clearIcon, forSearchBarIcon: .Clear, state: .Normal) // Add to nav bar searchBar.sizeToFit() navigationItem.titleView = searchBar 

在这里输入图像描述

不使用私人API:

 for (UIView* subview in [[self.searchBar.subviews lastObject] subviews]) { if ([subview isKindOfClass:[UITextField class]]) { UITextField *textField = (UITextField*)subview; [textField setBackgroundColor:[UIColor redColor]]; } } 

更好的解决方法是在UISearchBar设置UITextField的外观

 [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundColor:[UIColor grayColor]]; 

只需使用类别方法遍历所有视图(在iOS 7中validation,不使用私有API):

 @implementation UISearchBar (MyAdditions) - (void)changeDefaultBackgroundColor:(UIColor *)color { for (UIView *subview in self.subviews) { for (UIView *subSubview in subview.subviews) { if ([subSubview isKindOfClass:[UITextField class]]) { UITextField *searchField = (UITextField *)subSubview; searchField.backgroundColor = color; break; } } } } @end 

所以在将类别导入到类中之后,就像使用它一样:

 [self.searchBar changeDefaultBackgroundColor:[UIColor grayColor]]; 

请记住,如果将这个紧跟[[UISearchBar alloc] init]行之后,它将不能工作,因为search栏的子视图仍在创build。 在设置search栏的其余部分后,放下几行。

仅更改颜色:

 searchBar.tintColor = [UIColor redColor]; 

为了应用背景图像:

 [self.searchBar setSearchFieldBackgroundImage: [UIImage imageNamed:@"Searchbox.png"] forState:UIControlStateNormal]; 

苹果的方式呢?

 UISearchBar.appearance().setSearchFieldBackgroundImage(myImage, for: .normal) 

你可以在你的devise上设置任何图像!

但是如果你想创build所有的程序,你可以做到这一点


我在Swift 3上的解决scheme

 let searchFieldBackgroundImage = UIImage(color: .searchBarBackground, size: CGSize(width: 44, height: 30))?.withRoundCorners(4) UISearchBar.appearance().setSearchFieldBackgroundImage(searchFieldBackgroundImage, for: .normal) 

我在哪里使用助手扩展

 public extension UIImage { public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) { let rect = CGRect(origin: .zero, size: size) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cgImage = image?.cgImage else { return nil } self.init(cgImage: cgImage) } public func withRoundCorners(_ cornerRadius: CGFloat) -> UIImage? { UIGraphicsBeginImageContextWithOptions(size, false, scale) let rect = CGRect(origin: CGPoint.zero, size: size) let context = UIGraphicsGetCurrentContext() let path = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius) context?.beginPath() context?.addPath(path.cgPath) context?.closePath() context?.clip() draw(at: CGPoint.zero) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext(); return image; } } 
 - (void)viewDidLoad { [super viewDidLoad]; [[self searchSubviewsForTextFieldIn:self.searchBar] setBackgroundColor:[UIColor redColor]]; } - (UITextField*)searchSubviewsForTextFieldIn:(UIView*)view { if ([view isKindOfClass:[UITextField class]]) { return (UITextField*)view; } UITextField *searchedTextField; for (UIView *subview in view.subviews) { searchedTextField = [self searchSubviewsForTextFieldIn:subview]; if (searchedTextField) { break; } } return searchedTextField; } 

这是Swift版本(swift 2.1 / IOS 9)

 for view in searchBar.subviews { for subview in view.subviews { if subview .isKindOfClass(UITextField) { let textField: UITextField = subview as! UITextField textField.backgroundColor = UIColor.lightGrayColor() } } } 

对于iOS 9使用这个:

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. // Remove lag on oppening the keyboard for the first time UITextField *lagFreeField = [[UITextField alloc] init]; [self.window addSubview:lagFreeField]; [lagFreeField becomeFirstResponder]; [lagFreeField resignFirstResponder]; [lagFreeField removeFromSuperview]; //searchBar background color change [[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setBackgroundColor:[UIColor greenColor]]; [[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTextColor:[UIColor blackColor]; return YES; } 

Swift 3

 for subview in searchBar.subviews { for innerSubview in subview.subviews { if innerSubview is UITextField { innerSubview.backgroundColor = UIColor.YOUR_COLOR_HERE } } } 

对于Swift 3+,使用这个:

 for subView in searchController.searchBar.subviews { for subViewOne in subView.subviews { if let textField = subViewOne as? UITextField { subViewOne.backgroundColor = UIColor.red //use the code below if you want to change the color of placeholder let textFieldInsideUISearchBarLabel = textField.value(forKey: "placeholderLabel") as? UILabel textFieldInsideUISearchBarLabel?.textColor = UIColor.blue } } } 

@EvGeniy Ilyin EvGeniy Ilyin的解决scheme是最好的。 我基于这个解决scheme写了一个Objective-C版本。

创build一个UIImage类别,并在UIImage + YourCategory.h中宣传两个类方法

 + (UIImage *)imageWithColor:(UIColor *)color withSize:(CGRect)imageRect; + (UIImage *)roundImage:(UIImage *)image withRadius:(CGFloat)radius; 

UIImage + YourCategory.m中实现方法

 // create image with your color + (UIImage *)imageWithColor:(UIColor *)color withSize:(CGRect)imageRect { UIGraphicsBeginImageContext(imageRect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, imageRect); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } // get a rounded-corner image from UIImage instance with your radius + (UIImage *)roundImage:(UIImage *)image withRadius:(CGFloat)radius { CGRect rect = CGRectMake(0.0, 0.0, 0.0, 0.0); rect.size = image.size; UIGraphicsBeginImageContextWithOptions(image.size, NO, [UIScreen mainScreen].scale); UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius]; [path addClip]; [image drawInRect:rect]; image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } 

在你的ViewController制作你自己的UISearchBar

 CGRect rect = CGRectMake(0.0, 0.0, 44.0, 30.0); UIImage *colorImage = [UIImage imageWithColor:[UIColor yourColor] withSize:rect]; UIImage *finalImage = [UIImage roundImage:colorImage withRadius:4.0]; [yourSearchBar setSearchFieldBackgroundImage:finalImage forState:UIControlStateNormal];