自定义UISearchBar 适配IOS6和IOS7

考虑到统一ios6与ios7的界面风格,UISearchBar通过重自定义来实现,重写一个类继承自UISearchBar

1、效果图:

QQ20140819-1@2x

2、部分代码:
附注释说明

1
2
3
4
5
6
7
8
9
10
SASearchBar.h
#import <UIKit/UIKit.h>
 
@interface SASearchBar : UISearchBar
 
@property (nonatomic, strong)   UITextField     *textField;
 
@property (nonatomic, strong)   UIButton        *searchBtn;
 
@end

SASearchBar.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#import "SASearchBar.h"
@implementation SASearchBar
#pragma mark 初始化
- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        // 设置背景色为透明,这句在ios6中很重要!!
        self.backgroundColor = [UIColor clearColor];
        self.placeholder = @"搜索号码或姓名";
    }
    return self;
}
 
#pragma mark 调整子控件
- (void)layoutSubviews
{
    [super layoutSubviews];
 
    UIView *baseView = iOS7 ? [self.subviews firstObject] : self;
 
    // 移除背景图片
    [[baseView.subviews firstObject] removeFromSuperview];
 
    // 获取TextField
    self.textField = [baseView.subviews firstObject];
    self.textField.leftView = nil;
    self.textField.background = nil;
    self.textField.backgroundColor = [UIColor clearColor];
    self.textField.frame = CGRectMake(0, 0, baseView.frame.size.width - 30, 44);
 
    // 创建搜索按钮
    self.searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *searchIcn = [UIImage imageNamed:@"icon_invite_search_btn.png"];
    [self.searchBtn setImage:searchIcn forState:UIControlStateNormal];
    self.searchBtn.frame = CGRectMake(baseView.frame.size.width - 30, 10, 20, 20);
    [baseView addSubview:self.searchBtn];
 
    NSLog(@"%@", self.subviews);
}
 
#pragma mark 绘制背景图片
- (void)drawRect:(CGRect)rect
{
    UIImage *image = [UIImage resizeImage:@"textField_line_selected.png"];
    [image drawInRect:CGRectMake(0, 0, rect.size.width, rect.size.height)];
}
@end

3、素材下载:Resource

One thought on “自定义UISearchBar 适配IOS6和IOS7

  1. Pingback: UISearchBar内部结构 | 小龙虾博客 (Crayfish)

Leave a Reply