3

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

4

4 回答 4

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 

它对我有用:)

于 2012-05-09T10:24:02.713 回答
15

您可以使用 UIAppearance 方法

斯威夫特 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]; 
于 2015-10-10T09:04:30.113 回答
2

更经批准的 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];

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

在此处输入图像描述

当您开始输入文本时,它会替换占位符,但标签仍然存在:

在此处输入图像描述

于 2012-05-09T10:42:33.217 回答
1

请参阅这篇文章删除 UISearchbar 左侧的图像。没有公共 API 可以更改或删除放大镜,您应该只使用 UITextField。

于 2012-05-09T10:29:25.450 回答