How to change inside background color of UISearchBar component on iOS
Asked Answered
C

26

68

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

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

achieved UISearchBar customization

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

desired UISearchBar customization

This needs to be compatible with iOS 4.3+.

Cruzeiro answered 11/12, 2012 at 9:35 Comment(5)
try this https://mcmap.net/q/281964/-uisearchbar-clear-background-color-or-set-background-image-duplicateExalted
This is not ok. I want to get rid of white color inside component. Take a look at the question...Cruzeiro
@BorutTomazin test my code its work fine and here you can change the searchBar icon with 4 types of icon which i define in answer but you want to use white searchbar so just add image on the searchbaricon with another white searchbar icon and also add image as a background of UITextField of searchbarBrewer
Possible duplicate of UISearchBar: changing background color of input fieldWalkerwalkietalkie
For Swift 3. I found a solution here: Customize textfield easilyHorning
B
36

Use this code to change the searchBar's 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];
}

Use the below code to change the 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+):

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

Here you can set 4 types of UISearchBarIcon i.e.:

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

I hope this help you...

Brewer answered 11/12, 2012 at 10:8 Comment(4)
@BorutTomazin i just add the code for change the textfield backgroundcolor of searchbar and when i get output for search icon i'll also post code hope it help you...Brewer
This way is not a good way to do it. It can easily break your app in coming iOS updates. EDIT Sorry, just saw that the OP needed it to be compatible with iOS 4.Jinny
@Jinny this is give perfact output which he wants and its problem occure in bellow the version of 5.0 or 4.3 so its fine and if you have a solution then post the code dude i have this solution which may useful ...Brewer
not the best solution. see EvGeniy Ilyin's, which is way bellow the many ugly solutions. (cmd+F, search this page.) UISearchBar.appearance().setSearchFieldBackgroundImage(white‌​Image, for: .normal)Aesir
N
47

Just customize the text field itself.

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

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

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

Nga answered 10/10, 2013 at 0:1 Comment(9)
This would likely be considered using private API, so I'd be cautious submitting an app with this.Peg
Like @iWasRobbed mentioned, this is using private API that accesses hidden variable through KVC.Zamboanga
@iWasRobbed and please take a look at my answer, maybe that will be fine for youNara
cough this can be rejected from Apple because you're accessing private variables coughTiepolo
Still Working in the last ios versionKantianism
Best and simple solution! Thnx! =)Merv
in iOS 13: Terminating app due to uncaught exception 'NSGenericException', reason: 'Access to UISearchBar's _searchField ivar is prohibited. This is an application bug' .. this is now going to cause app crashes, so you should change the solution to continue getting upvotes!Castera
iOS 13 gives me: reason: 'Access to UISearchBar's _searchField ivar is prohibited. This is an application bug'Gezira
Although in iOS 13 onwards there is a public API _searchBar.searchTextFieldNimble
D
42

Details

  • Xcode Version 11.0 (11A420a), swift 5

UISearchBar customising sample

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

 searchBar.searchBarStyle = .prominent // or default

enter image description here

Result 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))
    }
}
Drawers answered 20/1, 2017 at 11:50 Comment(8)
This was killing me...thanks for pointing out that for minimal you had to do layer.backgroundColor...Purpose
One interesting problem with this solution is that when type is .minimal and one sets the background to white -> the background becomes grey. this is due to the fact that the top of the view is taken by an image named _UISearchBarSearchFieldBackgroundViewMiddleoftheroader
Can't understand. Can you show the code? I have no problem with setting searchBar.backgroundColor = .white.Drawers
Beautiful solution! Thank you.Bronez
For guys looking for a better solution, I recommend you read EvGeniy Ilyin's, which is way bellow the many ugly solutions. (cmd+F, search this page.) UISearchBar.appearance().setSearchFieldBackgroundImage(whiteImage, for: .normal)Aesir
iOS 11 for minimal searcher, setting .layer background doesn't work anymore. It seems there is an additional view on top of the textfield.Eveliaevelin
why we use layer for minimal searchBarStyle .? because when I remove backgroundColor without layer it not set the color that's why .Heavyduty
@ApoorvKhatreja it is possible. I will wait for the official Xcode release and then update the code.Drawers
N
39

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

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

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

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

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

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

Nara answered 12/8, 2014 at 8:58 Comment(4)
SearchBarStyle should be default! :)Hatch
This doesn't work for me, not even on default or minimal style (iOS 8).Sphene
Works but iOS 9 only. Here is the Swift equivalent: UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).backgroundColor = UIColor.darkGrayColor()Walkerwalkietalkie
@MaxMacLeod, thanks I have updated my answer based on what you postedNara
B
36

Use this code to change the searchBar's 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];
}

Use the below code to change the 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+):

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

Here you can set 4 types of UISearchBarIcon i.e.:

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

I hope this help you...

Brewer answered 11/12, 2012 at 10:8 Comment(4)
@BorutTomazin i just add the code for change the textfield backgroundcolor of searchbar and when i get output for search icon i'll also post code hope it help you...Brewer
This way is not a good way to do it. It can easily break your app in coming iOS updates. EDIT Sorry, just saw that the OP needed it to be compatible with iOS 4.Jinny
@Jinny this is give perfact output which he wants and its problem occure in bellow the version of 5.0 or 4.3 so its fine and if you have a solution then post the code dude i have this solution which may useful ...Brewer
not the best solution. see EvGeniy Ilyin's, which is way bellow the many ugly solutions. (cmd+F, search this page.) UISearchBar.appearance().setSearchFieldBackgroundImage(white‌​Image, for: .normal)Aesir
J
24

According to the UISearchBar documentation:

You should use this function for 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.

Jinny answered 11/12, 2012 at 10:33 Comment(1)
This is fine if I am targeting only iOS 5+ devices.Cruzeiro
K
20

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

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];
Kathrinekathryn answered 8/3, 2014 at 6:38 Comment(0)
C
17

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

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

}
Consignor answered 24/3, 2017 at 22:43 Comment(4)
This is surely the best and the most graceful way. Thanks! Saved my life.Aesir
This is the correct way. I was just about to post a version of this. Good work! Very Complete!Farflung
Maybe I am doing something wrong, but this sets the background image of the entire search bar and not the just the background image inside the text fieldWebfooted
Finally a solution that doesn't use the private API! I went with UISearchBar.appearance().setSearchFieldBackgroundImage(UIImage(), for: .normal) to completely remove the grey imageRollo
A
14

To do this on iOS 13+,

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

Do note that by default the searchTextField.borderStyle is set to roundedRect, which applies a slight gray overlay on top of the color that you will set. If this is undesired, do

searchController.searchBar.searchTextField.borderStyle = .none

This will get rid of the gray overlay, but also get rid of the rounded corners.

Anchie answered 29/8, 2019 at 20:34 Comment(1)
how to you change the place holder text color for iOS 13 ?Cliftonclim
H
7

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

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

Hescock answered 16/5, 2016 at 18:31 Comment(0)
A
6

without using private API's:

for (UIView* subview in [[self.searchBar.subviews lastObject] subviews]) {
    if ([subview isKindOfClass:[UITextField class]]) {
        UITextField *textField = (UITextField*)subview;
        [textField setBackgroundColor:[UIColor redColor]];
    }
}
Annabellannabella answered 7/11, 2013 at 12:39 Comment(1)
It doesn't use private API but it still relies on private implementation details (i.e. the internal view hierarchy of the search bar). This implementation could change at any time.Nozicka
I
6

try this in iOS13 in swift

@IBOutlet weak var searchBar: UISearchBar!
searchBar.barTintColor = .systemIndigo
searchBar.searchTextField.backgroundColor = .white
Iva answered 20/8, 2020 at 11:33 Comment(0)
A
5

For Changing Only Color :

searchBar.tintColor = [UIColor redColor];

For Applying Background Image :

[self.searchBar setSearchFieldBackgroundImage:
                          [UIImage imageNamed:@"Searchbox.png"]
                                     forState:UIControlStateNormal];
Aleuromancy answered 8/7, 2013 at 13:4 Comment(0)
K
5

A better solution is to set the appearance of the UITextField inside UISearchBar

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundColor:[UIColor grayColor]];
Khoisan answered 27/5, 2015 at 13:17 Comment(3)
sorry @JulianKról I just saw your answer now, didn't notice it beforeKhoisan
no problem, just noticed yours, and checked how it is different :)Nara
duplicates previous answerWalkerwalkietalkie
P
4

Just traverse all views using a category method (verified in iOS 7 and doesn't use private 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

So after importing the category into your class, just use it like:

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

Keep in mind, if you put this immediately after the [[UISearchBar alloc] init] line, it won't work yet since the subviews of the search bar are still being created. Put it a few lines down after you setup the rest of the search bar.

Peg answered 6/4, 2014 at 4:6 Comment(0)
S
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;
}
Sabaean answered 9/10, 2014 at 9:55 Comment(0)
A
3

This is the Swift version ( 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()
        }
    }
}
Autonomic answered 9/11, 2015 at 4:26 Comment(1)
This had no effect for me. But setting the textField.layer.backgroundColor does change the background color.Casals
W
3

Searchbar now has a new instance property SearchTextField starting iOS 13, 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]];
}
Wellmannered answered 27/11, 2019 at 6:41 Comment(0)
U
2

iOS 13, Swift 5

searchBar.searchTextField.backgroundColor = .gray
 searchBar.searchTextField.tintColor = .white
 searchBar.searchTextField.textColor = .white
Unmistakable answered 2/10, 2019 at 13:45 Comment(0)
K
1

For iOS 9 use this:

- (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;
}
Kashmiri answered 1/11, 2015 at 18:26 Comment(0)
H
1

Swift 3

for subview in searchBar.subviews {
    for innerSubview in subview.subviews {
        if innerSubview is UITextField {
            innerSubview.backgroundColor = UIColor.YOUR_COLOR_HERE
        }
    }
}
Henriquez answered 15/1, 2017 at 17:57 Comment(0)
I
1

For Swift 3+, use this:

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
        }
     }
}
Indult answered 31/3, 2017 at 8:54 Comment(0)
M
1

With Swift 4, I would recommend that you only do this, no additional code needed:

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

You can also change .prominent to .minimal should you not want the outer background to be grey.

Mcneely answered 19/1, 2019 at 11:25 Comment(0)
H
1

Use it to update search textfield backgroud_color for xcode10 and xcode11 working fine for me

[[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTextColor:[UIColor greenColor]];
Humblebee answered 20/1, 2020 at 12:19 Comment(0)
C
0

@EvGeniy Ilyin EvGeniy Ilyin's solution is the best. I wrote an Objective-C version based on this solution.

Create a UIImage category, and advertise two class methods in UIImage+YourCategory.h

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

Implement methods in 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;
}

Make your own UISearchBar in your 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];
Clothes answered 12/10, 2017 at 1:26 Comment(0)
A
0

This Worked for me.

- (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]];
}
Antithesis answered 23/10, 2018 at 5:46 Comment(0)
M
-1

This helped me to change the background color of textField in searchbar.

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = .white
Madigan answered 7/2, 2019 at 10:35 Comment(1)
Pleas don't just put some code, provide some explanation also.Frozen

© 2022 - 2024 — McMap. All rights reserved.