如何在IOS中实现普通搜索栏

时间:2013-10-15 07:39:06

标签: ios objective-c uisearchbar

我想删除默认搜索栏的边框并实现普通搜索栏。见下图

默认搜索栏,

Default Search Bar

这就是我想要实现的目标,

Plain Search bar

我用谷歌搜索并尝试下面的代码,但没有达到预期的效果,

for (id img in searchbar.subviews) 
{
    if ([img isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) 
    {
        [img removeFromSuperview];
    }
}

searchbar.delegate = self;
searchbar.layer.borderWidth = 0;
searchbar.layer.borderColor = [[UIColor clearColor] CGColor];

我该如何实现?

2 个答案:

答案 0 :(得分:1)

感谢您的回答。我用下面的代码解决了我的问题......

Plain White Search bar background image used in the below code

UITextField *txfSearchField = [self.searchbar valueForKey:@"_searchField"];
        [txfSearchField setBackgroundColor:[UIColor whiteColor]];
        [txfSearchField setLeftViewMode:UITextFieldViewModeNever];
        [txfSearchField setRightViewMode:UITextFieldViewModeNever];
        [txfSearchField setBackground:[UIImage imageNamed:@"searchbar_bgImg.png"]];
        [txfSearchField setBorderStyle:UITextBorderStyleNone];
        //txfSearchField.layer.borderWidth = 8.0f;
        //txfSearchField.layer.cornerRadius = 10.0f;
        txfSearchField.layer.borderColor = [UIColor clearColor].CGColor;
        txfSearchField.clearButtonMode=UITextFieldViewModeNever;

        [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setFont:[UIFont fontWithName:@"TimesNewRomanPS-BoldItalicMT" size:20]];
        [[UIBarButtonItem appearanceWhenContainedIn: [UISearchBar class], nil] setTintColor:[UIColor blackColor]];

答案 1 :(得分:0)

在iOS 7中有一个很小的变化,现在你必须迭代两个级别。

 for (UIView *subView in self.searchBar.subViews){
    for (UIView *2ndLeveSubView in subView.subViews){
    if ([2ndLevelSubView isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
        {
            [2ndLevelSubView removeFromSuperView];
        }
    }
   }