remove the border of uitextfield in uisearchbar

好久不见. 提交于 2019-12-06 09:17:12

问题


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.



来源:https://stackoverflow.com/questions/10601402/remove-the-border-of-uitextfield-in-uisearchbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!