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

问题描述 投票:56回答:21

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

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

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

这需要与iOS 4.3+兼容。

ios objective-c customization uisearchbar background-color
21个回答
33
投票

使用此代码更改搜索栏qazxsw poi background图片:

UITextField

使用以下代码更改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

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

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

在这里你可以设置4种类型的UISearchBar,即:

  1. - (void)setImage:(UIImage *)iconImage forSearchBarIcon:(UISearchBarIcon)icon state:(UIControlState)state
  2. UISearchBarIcon
  3. UISearchBarIconBookmark
  4. UISearchBarIconClear

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


6
投票

更好的解决方案是在enter image description here中设置for (UIView* subview in [[self.searchBar.subviews lastObject] subviews]) { if ([subview isKindOfClass:[UITextField class]]) { UITextField *textField = (UITextField*)subview; [textField setBackgroundColor:[UIColor redColor]]; } } 的外观

UITextField

5
投票

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

UISearchBar

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

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

请记住,如果您在@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 行之后立即放置它,它将无法工作,因为搜索栏的子视图仍在创建中。设置搜索栏的其余部分后,将其放下几行。


4
投票

仅更改颜色:

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

用于应用背景图像:

[[UISearchBar alloc] init]

3
投票
searchBar.tintColor = [UIColor redColor];

3
投票

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

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

1
投票

对于iOS 9使用此:

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

1
投票

斯威夫特3

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

1
投票

对于Swift 3+,请使用:

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

1
投票

使用Swift 4,我建议您只执行此操作,无需其他代码:

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

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


-1
投票

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

创建一个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 } } } 类,并在UIImage + YourCategory.h中公布两个类方法

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

在UIImage + YourCategory.m中实现方法

UIImage

在你的+ (UIImage *)imageWithColor:(UIColor *)color withSize:(CGRect)imageRect; + (UIImage *)roundImage:(UIImage *)image withRadius:(CGFloat)radius; 制作自己的// 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

48
投票

只需自定义文本字段。

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

UISearchBarIconResultsList

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


-1
投票

这对我有用。

ViewController

-2
投票

这有助于我在搜索栏中更改textField的背景颜色。

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

35
投票

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

目前(UISearchBarIconSearch)你可以这样做,只需一种颜色的情况,这样:

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

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

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

probably since iOS 5

如果您的项目支持iOS 9及更高版本,则不需要[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundColor:[UIColor redColor]];

如果您需要支持早期版本的iOS并想使用Swift,请查看if #available(iOS 9.0, *) { UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).backgroundColor = UIColor.darkGrayColor() } 问题。


32
投票

细节

  • Xcode 10.2(10E125)
  • 斯威夫特5

#available

this

用法

UISearchBar customising sample

结果1

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

结果2

 searchBar.searchBarStyle = .prominent // or default

enter image description here

完整样本

 searchBar.searchBarStyle = .minimal

23
投票

根据enter image description here

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

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

用法示例:

UISearchBar documentation

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


19
投票

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

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

13
投票

苹果方式怎么样?

[mySearchBar setSearchFieldBackgroundImage:myImage forState:UIControlStateNormal];

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

但是,如果您想以编程方式创建所有内容,则可以执行此操作


我在Swift 3上的解决方案

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

我在哪里使用助手扩展

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

7
投票

我发现这是使用let searchFieldBackgroundImage = UIImage(color: .searchBarBackground, size: CGSize(width: 44, height: 30))?.withRoundCorners(4) UISearchBar.appearance().setSearchFieldBackgroundImage(searchFieldBackgroundImage, for: .normal) 自定义Swift 2.2和iOS 8+中各种搜索栏属性外观的最佳方式

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

}

UISearchBarStyle.Minimal


6
投票

不使用私有API:

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
© www.soinside.com 2019 - 2024. All rights reserved.