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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13817330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:29:49  来源:igfitidea点击:

How to change inside background color of UISearchBar component on iOS

iosobjective-ccustomizationuisearchbarbackground-color

提问by Borut Tomazin

I know how to remove/change UISearchBarbackground color around search field:

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

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

achieved UISearchBar customization

实现 UISearchBar 自定义

But don't know how to do this inside it like that:

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

desired UISearchBar customization

所需的 UISearchBar 自定义

This needs to be compatible with iOS 4.3+.

这需要与 iOS 4.3+ 兼容。

采纳答案by Paras Joshi

Use this code to change the searchBar's UITextFieldbackgroundImage:

使用此代码更改 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];
}

Use the below code to change the UISearchBarIcon:

使用以下代码更改UISearchBarIcon

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

Also, to change the searchBar icon you can use the following built-in method on UISearchBar(which is available from iOS 5+):

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

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

Here you can set 4 types of UISearchBarIconi.e.:

在这里您可以设置 4 种类型的UISearchBarIconie:

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

I hope this help you...

我希望这能帮助你...

回答by AbuZubair

Just customize the text field itself.

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

I am simply doing this and it works fine for me (iOS 7).

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

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

This way you don't need to create an image, size it, etc...

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

回答by Julian Król

Solution which doesn't involve any private API ! :)

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

Currently (probably since iOS 5) you can do this, for simply one colour cases, in this way:

目前(可能从 iOS 5 开始)您可以通过以下方式执行此操作,仅适用于一种颜色的情况:

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

but please keep in mind that as it basis on appearance the change will be global for the app (it can be an advantage or a disadvantage of the solution).

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

For Swift you can use (it will work for iOS 9 and above):

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

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

You do not need #availableif your project supports iOS 9 and newer.

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

If you need to support earlier versions of iOS and want to use Swift take a look at thisquestion.

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

回答by Vasily Bodnarchuk

Details

细节

  • Xcode Version 11.0 (11A420a), swift 5
  • Xcode 版本 11.0 (11A420a),swift 5

UISearchBar customising sample

UISearchBar 自定义示例

Solution

解决方案

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

Usage

用法

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))

Result 1

结果 1

 searchBar.searchBarStyle = .prominent // or default

enter image description here

在此处输入图片说明

Result 2

结果 2

 searchBar.searchBarStyle = .minimal

enter image description here

在此处输入图片说明

Full sample

完整样品

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.setTextField(color: UIColor.green.withAlphaComponent(0.3))
    }
}

回答by Accatyyc

According to the UISearchBar documentation:

根据UISearchBar 文档

You should use this function for iOS 5.0+.

您应该在 iOS 5.0+ 上使用此功能。

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

Usage example:

用法示例:

[mySearchBar setSearchFieldBackgroundImage:myImage forState:UIControlStateNormal];

Sadly, in iOS 4 you need to revert to less sophisticated methods. See other answers.

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

回答by Nick H247

As Accatyyc says for iOS5+ use setSearchFieldBackgroundImage, but you either need to create a graphic, or do the following:

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

回答by EvGeniy Ilyin

what about apple way?

苹果的方式呢?

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

you can set any image on your design!

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

But if you want create all programmaticle, you ca do this

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



my solution on Swift 3

我在Swift 3 上的解决方案

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

where i use helpers extension

我在哪里使用助手扩展

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

}

回答by Alex Koshy

I've found this to be the best way to customize the appearance of various search bar attributes in Swift 2.2 and iOS 8+ using UISearchBarStyle.Minimal

我发现这是在 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

enter image description here

在此处输入图片说明

回答by Tomer Even

without using private API's:

不使用私有 API:

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

回答by Mahmoud Adam

A better solution is to set the appearance of the UITextFieldinside UISearchBar

更好的解决办法是设置UITextField里面的外观UISearchBar

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