如何更改UISearchBar以使用文本替换文本字段内的搜索图标

时间:2012-05-09 10:00:01

标签: iphone objective-c ios

我有UISearchBar,我想删除搜索标记(放大镜图标)并放置文本而不是它

4 个答案:

答案 0 :(得分:15)

您可以通过以下方式更改放大图标,根据您的需要进行调整: -

#import <UIKit/UIKit.h>

@interface SearchBoxExperimentsViewController : UIViewController {  
    IBOutlet UISearchBar *searchBar;
}
@end 

#import "SearchBoxExperimentsViewController.h"
@interface SearchBoxExperimentsViewController (Private)
- (void)setSearchIconToFavicon;
@end

@implementation SearchBoxExperimentsViewController
- (void)viewDidLoad 
{  
    [self setSearchIconToFavicon];  
    [super viewDidLoad];
}

#pragma mark Private
- (void)setSearchIconToFavicon 
{  
    // Really a UISearchBarTextField, but the header is private.  
    UITextField *searchField = nil;  
    for (UIView *subview in searchBar.subviews) {    
        if ([subview isKindOfClass:[UITextField class]]) {      
            searchField = (UITextField *)subview;      
            break;    
        }  
    }    
    if (searchField) {      
        UIImage *image = [UIImage imageNamed: @"favicon.png"];   
        UIImageView *iView = [[UIImageView alloc] initWithImage:image];    
        searchField.leftView = iView;    
        [iView release];  
    }  
}
@end 

它对我有用:)

答案 1 :(得分:15)

您可以使用UIAppearance方法

Swift 3.0

UISearchBar.appearance().setImage(UIImage(named: "image_name"), for: .search, state: .normal)

目标-C

[[UISearchBar appearance] setImage:[UIImage imageNamed:@"image_name"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal]; 

答案 2 :(得分:2)

更加认可的API-API友好是使用普通的UITextField,使用以下代码在UITextField中添加标签(如果你想删除放大镜,那么你对搜索框的吸引力是什么?) :

UILabel *searchFieldLeftLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 32, 15)];
searchFieldLeftLabel.text = @"find:";
searchFieldLeftLabel.placeholder = @"e.g. wings, Boathouse";
searchFieldLeftLabel.font = [UIFont systemFontOfSize:14];
searchFieldLeftLabel.textColor = [UIColor grayColor];
self.searchFieldLeftLabel.leftView = locationSearchFieldLeftLabel;
[searchFieldLeftLabel release];

结果是一个漂亮的文本框,如下所示:

enter image description here

当您开始键入文本时,它会替换占位符,但标签仍为:

enter image description here

答案 3 :(得分:1)

请参阅此帖Removing the image on the left of an UISearchbar。没有公共API可以更改或删除放大镜,您只需使用UITextField。