自定义搜索框

自定义搜索框

搜索框

1
2
3
4
5
6
7
8
9
10
11
12
#import <UIKit/UIKit.h>

@interface CustomSearchBar : UIView

//以便外部修改UI
@property(nonatomic,strong) UITextField *textField;
@property(nonatomic,strong) UITextField *bgView;

//声明一个类方法,快速创建一个自定义的view
+(instancetype)searchBar;

@end
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//
// CustomSearchBar.m
// RuntimeLearn
//
// Created by luo.h on 16/3/14.
// Copyright © 2016年 appledev. All rights reserved.
//

#define RGBCOLOR(r,g,b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1]

#import "CustomSearchBar.h"

@interface CustomSearchBar ()

@end


@implementation CustomSearchBar


- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self addSubview:self.bgView];
[self addSubview:self.textField];
}
return self;
}


+(instancetype)searchBar
{
return [[self alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44)];
}


- (UITextField *)textField {
if(_textField == nil) {
_textField = [[UITextField alloc] init];
_textField.font = [UIFont systemFontOfSize:15];
_textField.placeholder = @"搜索";

UIImageView *searchIcon = [[UIImageView alloc] init];
searchIcon.image = [UIImage imageNamed:@"search_search_icon"];
// contentMode:default is UIViewContentModeScaleToFill,要设置为UIViewContentModeCenter:使图片居中,防止图片填充整个imageView
searchIcon.contentMode = UIViewContentModeCenter;

CGRect frame = CGRectZero;
frame.size = CGSizeMake(30, 30);
searchIcon.frame =frame;

_textField.leftView = searchIcon;
_textField.leftViewMode = UITextFieldViewModeAlways;
_textField.frame=CGRectMake(5, 5,self.bounds.size.width-10, self.bounds.size.height-10);

_textField.backgroundColor=[UIColor whiteColor];
_textField.layer.borderColor=RGBCOLOR(200, 200, 200).CGColor;
_textField.layer.borderWidth=1;

//设置圆角效果
_textField.layer.cornerRadius = (self.bounds.size.height-10)/2;
_textField.layer.masksToBounds = YES;
}
return _textField;
}


- (UIView *)bgView {
if(_bgView == nil) {
//背景视图
_bgView = [[UIView alloc] initWithFrame:self.bounds];
_bgView.backgroundColor =RGBCOLOR(225, 227, 234);
}
return _bgView;
}

@end

文章作者: kyren
文章链接: http://huluo666.github.io/2016/03/24/自定义搜索框/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Kyren's Blog