remove the border of uitextfield in uisearchbar

2020-07-26 10:47发布

I wanna custom the UISearchBar control to a style as showed in the picture below: It's a customed UISearchBar, there is no boarder for the textfield here.

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. :(

enter image description here

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!

2条回答
成全新的幸福
2楼-- · 2020-07-26 11:25

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];
                }
            }
        }
    }
}
查看更多
Melony?
3楼-- · 2020-07-26 11:26

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.

查看更多
登录 后发表回答