Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to figure out how to add a 1 pixel stroke gray border to my UISearchBar in my app. The Facebook Messenger app accomplishes this quite well. (see pic below).

I know there is a background image property of UISearchBar, but I believe that is not the right thing to use, as it stretches the image out and repeats it across the entire view of the search bar.

I'd greatly appreciate pointers in the right direction.

enter image description here

like image 325
klcjr89 Avatar asked Jan 17 '14 17:01

klcjr89


3 Answers

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

like image 76
Rashid Latif Avatar answered Nov 09 '22 07:11

Rashid Latif


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;
        }
    }
}
like image 12
iOS Dev Avatar answered Nov 09 '22 08:11

iOS Dev


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

like image 11
Yaroslav Bai Avatar answered Nov 09 '22 07:11

Yaroslav Bai