Search code examples
iosobjective-cuiviewios7uisearchbar

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


Solution

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