可以自定义一个UITextFiled文本框,设置这些文本框的属性,具体看代码的注释。
.h文件
#import <UIKit/UIKit.h>
@interface OneSearBar : UITextField
@end
.m文件中
#import "OneSearBar.h"
#import "UIImage+Extend.h"
@implementation OneSearBar
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.background = [UIImage resizedImageWithName:@"搜索框背景图"];
//self.borderStyle=UITextBorderStyleRoundedRect;
UIImage *searchImage = [UIImage imageNamed:@"搜索"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:searchImage];
imageView.bounds = CGRectMake(200, 0, 20, 20);
imageView.contentMode = UIViewContentModeCenter;//设置图片居中显示
self.leftView = imageView;
self.leftViewMode = UITextFieldViewModeAlways;
self.font = [UIFont systemFontOfSize:14.0];
//初始化一个空的可变字典
NSMutableDictionary *attributed = [NSMutableDictionary dictionary];
attributed[NSForegroundColorAttributeName] = [UIColor grayColor];
attributed[NSFontAttributeName] = [UIFont systemFontOfSize:14.0];
attributed[NSUnderlineStyleAttributeName]=[NSNumber numberWithInt:NSUnderlineStyleNone];//设置下划线的大小
/*下划线种类
NSUnderlineStyleNone 无下划线
NSUnderlineStyleSingle 单行下划线
NSUnderlineStyleThick 粗的下划线
NSUnderlineStyleDouble 双下划线
*/
self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"大家都在搜索" attributes:attributed];
self.clearButtonMode = UITextFieldViewModeAlways;//设置UISearchBar的在进行输入的时候会出现一个✘的按钮,设置为总是出现。
self.returnKeyType = UIReturnKeySearch;//设置return键为搜索按钮
self.enablesReturnKeyAutomatically = YES;//设置无文字就不可点击搜索
//通过NSAttributedString实现,自定义一个继承至UITextField的类
//NSAttributedString它由2部分组成 文字内容 : NSString * 文字属性: NSDictionary *
/*文字颜色 - NSForegroundColorAttributeName
字体大小 - NSFontAttributeName
下划线 - NSUnderlineStyleAttributeName
背景色 - NSBackgroundColorAttributeName
*/
}
return self;
}
@end