How to add a 1 pixel gray border around a UISearchBar TextField

This work fine:

UITextField *txtSearchField = [yourSearchBar valueForKey:@"_searchField"];
[txtSearchField setBorderStyle:UITextBorderStyleRoundedRect];
txtSearchField.layer.cornerRadius = 4;
txtSearchField.layer.borderWidth = 1.0f;
txtSearchField.layer.borderColor = [[UIColor colorWhatYouWant] CGColor]; 

do not forget #import <QuartzCore/QuartzCore.h>


Swift 3 version

override func viewDidLoad() {
    super.viewDidLoad()

    for s in searchBar.subviews[0].subviews {
        if s is UITextField {
            s.layer.borderWidth = 1.0
            s.layer.borderColor = UIColor.gray.cgColor
        }
    }
}

To make it round you can use textField.layer.cornerRadius property


Swift 5

Easy way to do

    @IBOutlet private weak var searchBar:UISearchBar!{
        didSet{
            if let searchTextfield = self.searchBar.value(forKey: "searchField") as? UITextField  {
                searchTextfield.layer.borderColor = UIColor.lightGray.cgColor
                searchTextfield.layer.borderWidth = 1
                searchTextfield.layer.cornerRadius = 10
            }
        }
    }

enter image description here


Try this code:

//First add the following import and macro:
#import <QuartzCore/QuartzCore.h>
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

//Then change yourSearchBar border: 
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0"))
{
    for (id object in [[[yourSearchBar subviews] objectAtIndex:0] subviews])
    {
        if ([object isKindOfClass:[UITextField class]])
        {
            UITextField *textFieldObject = (UITextField *)object;
            textFieldObject.layer.borderColor = [[UIColor grayColor] CGColor];
            textFieldObject.layer.borderWidth = 1.0;
            break;
        }
    }
}
else
{
    for (id object in [yourSearchBar subviews])
    {
        if ([object isKindOfClass:[UITextField class]])
        {
            UITextField *textFieldObject = (UITextField *)object;
            textFieldObject.layer.borderColor = [[UIColor grayColor] CGColor];
            textFieldObject.layer.borderWidth = 1.0;
            break;
        }
    }
}