自定义搜索框

封装的几种方法
  1. 分类:UITextField/UISearchBar
  2. 自定义控件
  3. 工具类

从上到下优先度依次降低.

用哪种方式封装

通过分类,如果通过分类[UITextField searchBar]方法名跟类名明显对不上号;[UISearchBar searchBar]返回结果是一个UITextField,跟类名也对不上.所以我们需要自定控件,自定义控件就需要继承UITextField.

代码

CTSearchBar.h 文件

#import <UIKit/UIKit.h>

@interface CTSearchBar : UITextField
+ (instancetype)searchBar;
@end

CTSearchBar.m

#import "CTSearchBar.h"

@implementation CTSearchBar

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.font = [UIFont systemFontOfSize:15];
        self.placeholder = @"请输入搜索内容";
        self.clearsOnBeginEditing = YES;
        self.clearButtonMode = UITextFieldViewModeAlways;

        UIImage *image = [UIImage imageNamed:@"searchbar_textfield_search_icon"];
        UIImageView *searchIcon = [[UIImageView alloc] initWithImage:image];
        searchIcon.width = 30;
        searchIcon.height = 30;
        searchIcon.contentMode = UIViewContentModeCenter;

        self.leftView = searchIcon;
        self.leftViewMode = UITextFieldViewModeAlways;
    }
    return self;
}

+ (instancetype)searchBar {
    return [[self alloc] init];
}
@end
调用方式
- (void)viewDidLoad {
    [super viewDidLoad];

    UITextField *searchBar = [CTSearchBar searchBar];
    searchBar.width = 500;
    searchBar.height = 35;
    self.navigationItem.titleView = searchBar;
}

上面代码中searchBar.width = 500;这种方式是因为我给UIView做了一个分类,所以可以直接赋值.详见:通过Category让UIView更方便的布局

以上仅提供简单思路,还可以封装更加复杂的搜索框,像新浪微博的.

--EOF--