remove the border of uitextfield in uisearchbar

2020-07-26 11:02发布

问题:

I wanna custom the UISearchBar control to a style as showed in the picture below:

First I should remove the background view, then find out the UITextfiled in UISearchBar, extend the frame of UITextfiled and remove the boarder of it.

Here is my code :

UITextField *searchField;

NSUInteger numViews = [self.subviews count];
for(int i = 0; i != numViews; i++) {
    if([[self.subviews objectAtIndex:i] isKindOfClass:[UITextField class]]) { //conform?
        searchField = [self.subviews objectAtIndex:i];
    }
}
if(!(searchField == nil)) {

    [searchField setBorderStyle:UITextBorderStyleNone];
    searchField.frame = self.frame; //modify the frame
}

[[self.subviews objectAtIndex:0]removeFromSuperview]; //remove the background.

The result is the boarder of the UITextField is still there. :(

My question is : 1.Why can not I modify the appearance of the UITextField of UISearchBar?

2.How to remove the boarder of UITextfield in UISearchBar.

Thanks very much!

回答1:

Subclass UISearchBar and override layoutSubViews to remove the search bar background and the text field border subviews:

- (void)layoutSubviews
{    
    [super layoutSubviews];

    for (UIView *subview in self.subviews) {
        // Remove the default background
        if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
            [subview removeFromSuperview];
        }

        // Remove the rounded corners
        if ([subview isKindOfClass:NSClassFromString(@"UITextField")]) {
            UITextField *textField = (UITextField *)subview;
            for (UIView *subsubview in textField.subviews) {
               if ([subsubview isKindOfClass:NSClassFromString(@"UITextFieldBorderView")]) {
                    [subsubview removeFromSuperview];
                }
            }
        }
    }
}


回答2:

I'm not certain about this, however I suspect the only way you're going to be able to achieve a UISearchBar like that of the one in your image is to create a new subclass of UISearchBar. Using that you could set it up to look exactly like the one in your image.

This post may be of some help to you if you decide to go down the route of subclassing.