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.
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
}
}
}
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;
}
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With