自定义UISearchbar

时间:2013-08-29 12:13:58

标签: ios objective-c uisearchbar uisearchbardelegate

我正在尝试像这样自定义搜索栏 enter image description here

到目前为止,我已经成功完成了这个

enter image description here 现在我需要知道如何在右侧添加图像,塑造角落以及将背景更改为图像。到目前为止这是我的代码。我可以在UITextField的帮助下做到这一点,但我想使用UISearchBar来做到这一点。任何帮助?

   - (void)setSearchIconToFavicon 
    {  
        // commented are the things I tried out 
        UITextField *searchField = nil;  
        for (UIView *subview in searchBar.subviews)
        {    
            if ([subview isKindOfClass:[UITextField class]]) 
            {      
                searchField = (UITextField *)subview;      
                break;    
            }  
        }    
        if (searchField) 
        {      
            UIImage *image = [UIImage imageNamed: @"search_btn.png"];   
            UIImageView *iView = [[UIImageView alloc] initWithImage:image]; 
            //UIImage *image2 = [UIImage imageNamed: @"search_next_btn.png"];   
            //UIImageView *iView2 = [[UIImageView alloc] initWithImage:image2];  
            searchField.leftView = iView;    
            //searchField.rightView=iView2;
            [[self.searchBar.subviews objectAtIndex:0] removeFromSuperview];
            searchField.textColor = [UIColor grayColor];
        }  
  }

2 个答案:

答案 0 :(得分:0)

您可以替换书签图像,并在必要时调整其偏移量。就像这样..

[self.searchDisplayController.searchBar setImage:[UIImage imageNamed:@"yourImage"] forSearchBarIcon:UISearchBarIconBookmark state:UIControlStateNormal];
[self.searchDisplayController.searchBar setPositionAdjustment:UIOffsetMake(0, 0) forSearchBarIcon:UISearchBarIconBookmark];

您可以在委托方法中处理按钮事件:

- (void)searchBarBookmarkButtonClicked:(UISearchBar *)searchBar

我希望你明白我的意思。

答案 1 :(得分:0)

如果你的目标应用程序是> = 5.0来改变搜索栏的背景图像,你可以使用这行代码。

[[UISearchBar appearance] setSearchFieldBackgroundImage:[UIImage imageNamed:@"searchbar.png"]forState:UIControlStateNormal];