自定义搜索框

  默认状况下,苹果给咱们的搜索框🔍并非咱们想要的效果,因此咱们可能就须要去自定义一个本身须要的搜索框,下面简单写一个自定义的控件。html

  要注意:ide

  一、searchIcon.height = 30;这里的控件尺寸直接赋值是由于在头文件中引入UIView的类别 :http://www.cnblogs.com/daomul/p/4662402.htmlspa

  二、采用instancetype单例模式加载控件code

  三、leftView是左边的一个🔍图片,contentMode是图片控件的填充方式,为了使得图片居中显示orm

  四、是基于UITextField的htm

 

  五、那么咱们在咱们对应父控制器中就能够经过以下代码调用:blog

    

      //自定义搜索框图片

        XBSearchBar *searchBar = [XBSearchBar searchBar];animation

        searchBar.width = 300;it

        searchBar.height = 30;    

       //设置为navigation的正中位置

        self.navigationItem.titleView = searchBar;

头文件代码:

  

//
//  XBSearchBar.h
//  XibaTest
//
//  Created by bos on 15-6-14.
//  Copyright (c) 2015年 axiba. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface XBSearchBar : UITextField

+(instancetype)searchBar;

@end

 

文件代码:

 1 //
 2 //  XBSearchBar.m
 3 //  XibaTest
 4 //
 5 //  Created by bos on 15-6-14.
 6 //  Copyright (c) 2015年 axiba. All rights reserved.
 7 //
 8 
 9 #import "XBSearchBar.h"
10 
11 @implementation XBSearchBar
12 
13 -(id)initWithFrame:(CGRect)frame
14 {
15     self = [super initWithFrame:frame];
16     
17     if (self) {
18         
19         self.font = [UIFont systemFontOfSize:15];
20         self.placeholder = @"请输入搜索条件...";
21         self.background = [UIImage imageNamed:@"searchbar_textfield_background"];
22         
23         UIImageView *searchIcon = [[UIImageView alloc]init];
24         searchIcon.height = 30;
25         searchIcon.width = 30;
26         //控制图片控件内部的填充方式
27         searchIcon.contentMode = UIViewContentModeCenter;
28         searchIcon.image = [UIImage imageNamed:@"searchbar_textfield_search_icon"];
29         
30         self.leftView = searchIcon;
31         self.leftViewMode = UITextFieldViewModeAlways;
32         
33     }
34     return self;
35 }
36 
37 +(instancetype)searchBar
38 {
39     return [[self alloc]init];
40 }
41 
42 /*
43 // Only override drawRect: if you perform custom drawing.
44 // An empty implementation adversely affects performance during animation.
45 - (void)drawRect:(CGRect)rect {
46     // Drawing code
47 }
48 */
49 
50 @end
相关文章
相关标签/搜索