UISearchBar背景图像奇怪地工作

时间:2015-01-06 07:51:49

标签: xcode ios8 uisearchbar

我希望像这样做一个简单的单色搜索栏:

enter image description here

通过将此图像设置为背景图像,我已成功在视图控制器中执行此操作:

enter image description here

并使用此代码:

 [self.searchBar setTranslucent:NO];
 [self.searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"searchbg.png"] forState:UIControlStateNormal];

然而,当我点击搜索栏并进入searchdisplaycontroller时,它看起来像这样:

enter image description here

那里有一个白色的部分我无法摆脱。我试过这样做:

[self.searchDisplayController.searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"searchbg.png"] forState:UIControlStateNormal];

但它似乎不起作用。我有点不解为什么他们的行为不同,因为他们都是uisearchbars?

感谢。

1 个答案:

答案 0 :(得分:0)

尝试为UISearchBar图层设置borderColor和borderWidth,它将修复您的颜色变化 请记住,你必须记住,对于ios7和以后的视图位置是不同的,所以使用如下所述。我也有UISearchBar的子类,如果你想要你也创建一个或用你的serachBar替换self

- (void)setup
{
    self.placeholder       = @"Search Products";

    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
        self.backgroundColor = [UIColor lightGrayColor];
        UIView *topView = self.subviews[0];
        [self searchBarCustomization:topView.subviews];
    } else {
        self.backgroundImage = [UIImage imageWithColor:[UIColor lightGrayColor]];
        self.layer.borderColor = [UIColor lightGrayColor].CGColor;
        self.layer.borderWidth = 0.0;
        [self searchBarCustomization:self.subviews];
    }
}

- (void)searchBarCustomization:(NSArray *)subViews
{
     for (UIView *subView in subViews) {
         if ([subView isKindOfClass:[UITextField class]]) {
             [self customSearchBarField:subView];
         }
         if ([subView isKindOfClass:[UIButton class]]) {
             [self customSearchCancelButton:subView];
        }
     }
}

- (void)customSearchBarField:(id)searchBarField
{
    UITextField *searchField = (UITextField *) searchBarField;
    if (!SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
        searchField.background = [UIImage imageWithColor:[UIColor whiteColor]];
        searchField.borderStyle = UITextBorderStyleNone;
        searchField.layer.cornerRadius = 5.0;
    }
}