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

时间:2012-12-11 09:35:23

标签: ios objective-c customization uisearchbar background-color

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

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

achieved UISearchBar customization

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

desired UISearchBar customization

这需要与iOS 4.3 +兼容。

25 个答案:

答案 0 :(得分:48)

只需自定义文本字段。

我只是这样做,它对我来说很好(iOS 7)。

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

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

答案 1 :(得分:35)

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

目前(probably since iOS 5)您可以这样做,只需一种颜色案例,就这样:

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

但请记住,因为它基于外观,应用程序的全局变化(它可能是解决方案的优势或劣势)。

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

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

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

如果您需要支持早期版本的iOS并希望使用Swift,请查看this问题。

答案 2 :(得分:33)

使用此代码更改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种UISearchBarIcon,即:

  1. UISearchBarIconBookmark
  2. UISearchBarIconClear
  3. UISearchBarIconResultsList
  4. UISearchBarIconSearch
  5. 我希望这可以帮助你...

答案 3 :(得分:31)

详细

  • Xcode 10.2(10E125)
  • Swift 5

UISearchBar customising sample

解决方案

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

enter image description here

结果2

 searchBar.searchBarStyle = .minimal

enter image description here

完整样本

import UIKit

class ViewController: UIViewController {

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

答案 4 :(得分:23)

根据UISearchBar documentation

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

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

用法示例:

[mySearchBar setSearchFieldBackgroundImage:myImage forState:UIControlStateNormal];

可悲的是,在iOS 4中,您需要恢复不太复杂的方法。请参阅其他答案。

答案 5 :(得分:18)

正如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];

答案 6 :(得分:13)

苹果方式怎么样?

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

您可以在设计中设置任何图像!

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

我的解决方案 Swift 3

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

}

答案 7 :(得分:7)

我发现这是使用UISearchBarStyle.Minimal

自定义Swift 2.2和iOS 8+中各种搜索栏属性外观的最佳方式
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

enter image description here

答案 8 :(得分:6)

更好的解决方案是在UITextField

中设置UISearchBar的外观
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundColor:[UIColor grayColor]];

答案 9 :(得分:6)

不使用私有API:

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

答案 10 :(得分: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

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

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

请注意,如果您在[[UISearchBar alloc] init]行之后立即 ,那么它将无法使用,因为搜索栏的子视图仍在创建中。在设置搜索栏的其余部分后,将它放下几行。

答案 11 :(得分:4)

迅速在iOS13中尝试

@IBOutlet weak var searchBar: UISearchBar!
searchBar.barTintColor = .systemIndigo
searchBar.searchTextField.backgroundColor = .white

答案 12 :(得分:4)

仅更改颜色:

searchBar.tintColor = [UIColor redColor];

用于应用背景图像:

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

答案 13 :(得分:3)

这是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()
        }
    }
}

答案 14 :(得分:3)

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

searchController.searchBar.searchTextField.backgroundColor = // your color here

请注意,默认情况下,searchTextField.borderStyle设置为roundedRect,这将在您要设置的颜色上应用一点灰色叠加层。如果不希望这样做,

searchController.searchBar.searchTextField.borderStyle = .none

这将消除灰色的覆盖层,但也消除圆角。

答案 15 :(得分:3)

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

答案 16 :(得分:1)

Swift 3

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

答案 17 :(得分:1)

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

答案 18 :(得分:1)

对于Swift 3+,请使用:

{{1}}

答案 19 :(得分:1)

对于Swift 4,我建议您仅执行此操作,而无需其他代码:

self.searchBar.searchBarStyle = .prominent
self.searchBar.barStyle = .black

如果您不希望外部背景为灰色,也可以将.prominent更改为.minimal。

答案 20 :(得分:0)

Searchbar现在具有从iOS 13开始的新实例属性SearchTextField。 https://developer.apple.com/documentation/uikit/uisearchbar/3175433-searchtextfield

if(@available(iOS 13, *))
    searchBar.searchTextField.backgroundColor = [UIColor whiteColor];
    searchBar.searchTextField.textColor = [UIColor blackColor];
else{
    //API that supports below iOS 13
    //This will set it for all the UISearchBars in your application
    [[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setBackgroundColor:[UIColor whiteColor]];
    [[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTextColor:[UIColor blackColor]];
}

答案 21 :(得分:-1)

@EvGeniy Ilyin EvGeniy Ilyin的解决方案是最好的。 我根据此解决方案编写了 Objective-C 版本。

创建一个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;
}

UISearchBar

中制作自己的ViewController
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];

答案 22 :(得分:-1)

这对我有用。

- (void)setupSearchBar
{
    [self.searchBar setReturnKeyType:UIReturnKeySearch];
    [self.searchBar setEnablesReturnKeyAutomatically:NO];
    [self.searchBar setPlaceholder:FOLocalizedString(@"search", nil)];
    [self.searchBar setBackgroundImage:[UIImage new]];
    [self.searchBar setBackgroundColor:[UIColor myGreyBGColor]];
    [self.searchBar setBarTintColor:[UIColor myGreyBGColor]];
    [self.searchBar setTintColor:[UIColor blueColor]];
}

答案 23 :(得分:-1)

这帮助我更改了搜索栏中textField的背景颜色。

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = .white

答案 24 :(得分:-1)

iOS 13,Swift 5

searchBar.searchTextField.backgroundColor = .gray
 searchBar.searchTextField.tintColor = .white
 searchBar.searchTextField.textColor = .white