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

Bor*_*zin 61 customization objective-c background-color uisearchbar ios

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

[[self.searchBar.subviews objectAtIndex:0] removeFromSuperview];
self.searchBar.backgroundColor = [UIColor grayColor];
Run Code Online (Sandbox Code Playgroud)

实现了UISearchBar定制

但是不知道如何在里面这样做:

期望的UISearchBar定制

这需要与iOS 4.3+兼容.

Abu*_*air 47

只需自定义文本字段.

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

UITextField *txfSearchField = [_searchBar valueForKey:@"_searchField"];
txfSearchField.backgroundColor = [UIColor redColor];
Run Code Online (Sandbox Code Playgroud)

这样您就不需要创建图像,调整大小等等......

  • 这可能会考虑使用私有API,因此我谨慎提交应用程序. (15认同)

Jul*_*ról 37

解决方案不涉及任何私有API!:)

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

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundColor:[UIColor redColor]];
Run Code Online (Sandbox Code Playgroud)

但请记住,因为它的外观基础是应用程序的全局变化(它可能是解决方案的优点或缺点).

对于Swift,您可以使用(它适用于iOS 9及更高版本):

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

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

如果您需要支持早期版本的iOS并想使用Swift,请查看问题.

  • 这对我来说不起作用,甚至不是默认或最小样式(iOS 8). (19认同)

Vas*_*huk 36

Swift 3,xcode 8.2.1

UISearchBar定制样本

完整样本

UISearchBar扩展

import UIKit

extension UISearchBar {
    func getTextField() -> UITextField? { return value(forKey: "searchField") as? UITextField }
    func setTextField(color: UIColor) {
        guard let textField = getTextField() else { return }
        switch searchBarStyle {
        case .minimal:
            textField.layer.backgroundColor = color.cgColor
            textField.layer.cornerRadius = 6
        case .prominent, .default: textField.backgroundColor = color
        @unknown default: break
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法

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.setTextField(color: UIColor.green.withAlphaComponent(0.3))
Run Code Online (Sandbox Code Playgroud)

结果1

 searchBar.searchBarStyle = .prominent // or default
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

结果2

 searchBar.searchBarStyle = .minimal
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 这简直要了我的命……感谢您指出,至少你必须做layer.backgroundColor…… (2认同)
  • 此解决方案的一个有趣问题是,当type为.minimal且将背景设置为白色时 - >背景变为灰色.这是因为视图的顶部是由名为_UISearchBarSearchFieldBackgroundView的图像拍摄的 (2认同)

Par*_*shi 34

使用此代码更改searchBar的UITextFieldbackgroundImage:

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];
}
Run Code Online (Sandbox Code Playgroud)

使用以下代码更改UISearchBarIcon:

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

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

- (void)setImage:(UIImage *)iconImage forSearchBarIcon:(UISearchBarIcon)icon state:(UIControlState)state
Run Code Online (Sandbox Code Playgroud)

在这里你可以设置4种类型UISearchBarIcon:

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

我希望这有助于你......

  • 是的,这就是我想要的。谢谢! (2认同)

Acc*_*yyc 23

根据UISearchBar文档:

您应该将此功能用于iOS 5.0+.

- (void)setSearchFieldBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state
Run Code Online (Sandbox Code Playgroud)

用法示例:

[mySearchBar setSearchFieldBackgroundImage:myImage forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

遗憾的是,在iOS 4中,您需要恢复不太复杂的方法.看到其他答案.


Nic*_*247 20

正如Accatyyc所说的iOS5 +使用setSearchFieldBackgroundImage,但你需要创建一个图形,或者执行以下操作:

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];
Run Code Online (Sandbox Code Playgroud)


EvG*_*yin 15

苹果方式怎么样?

UISearchBar.appearance().setSearchFieldBackgroundImage(myImage, for: .normal)
Run Code Online (Sandbox Code Playgroud)

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

但是如果你想创建所有的程序,你可以这样做


我在Swift 3上的解决方案

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

我在哪里使用助手扩展

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 也许我做错了,但这会设置整个搜索栏的背景图像,而不仅仅是文本字段内的背景图像 (3认同)

Apo*_*eja 14

要在 iOS 13+ 上执行此操作,

searchController.searchBar.searchTextField.backgroundColor = // your color here
Run Code Online (Sandbox Code Playgroud)

请注意,默认情况下searchTextField.borderStyle设置为roundedRect,这会在您将设置的颜色之上应用轻微的灰色覆盖。如果这是不希望的,请执行

searchController.searchBar.searchTextField.borderStyle = .none
Run Code Online (Sandbox Code Playgroud)

这将摆脱灰色覆盖,但也摆脱圆角。


Ale*_*shy 8

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

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
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Tom*_*ven 6

不使用私有API:

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


Mah*_*dam 6

更好的解决方案是设置UITextField内部的外观UISearchBar

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundColor:[UIColor grayColor]];
Run Code Online (Sandbox Code Playgroud)


Pus*_*raj 5

仅更改颜色:

searchBar.tintColor = [UIColor redColor];
Run Code Online (Sandbox Code Playgroud)

应用背景图像:

[self.searchBar setSearchFieldBackgroundImage:
                          [UIImage imageNamed:@"Searchbox.png"]
                                     forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)


iwa*_*bed 5

只需使用类别方法遍历所有视图(在iOS 7中验证并且不使用私有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
Run Code Online (Sandbox Code Playgroud)

因此,在将类别导入您的类后,只需使用它:

[self.searchBar changeDefaultBackgroundColor:[UIColor grayColor]];
Run Code Online (Sandbox Code Playgroud)

请记住,如果您在行之后立即放置[[UISearchBar alloc] init]它,它将无法工作,因为仍在创建搜索栏的子视图.设置搜索栏的其余部分后,将其放下几行.


San*_*and 5

在 iOS13 中快速尝试这个

@IBOutlet weak var searchBar: UISearchBar!
searchBar.barTintColor = .systemIndigo
searchBar.searchTextField.backgroundColor = .white
Run Code Online (Sandbox Code Playgroud)