标签:
ios中导航条SearchBar控件虽然说很好用,但是有的时候控件的样式不能达到我们的需要,比如我们需要导航条的右侧有个放大镜,系统提供的控件没有这样的,这就需要我们自定义一个这样的searchBar了.
1,因为searchBar控件输入的时候和textField想似,所以我们自定义的控件继承与textField,起名字为searchView
我们可以看一下searchView.h里面的内容
1 #import <UIKit/UIKit.h> 2 3 @interface searchView : UITextField 4 5 @end
2,首先我们要在searchView.m里面实现初始化方法:
1 -(id)initWithFrame:(CGRect)frame 2 { 3 self = [super initWithFrame:frame]; 4 if(self){ 5 [self searchView]; //调用searchView方法 6 } 7 } 8 9 #pragma mark 实现searchView方法 10 -(void)searchView 11 { 12 self.placeholder = @"搜索店铺或者商品"; 13 //设置textField的样式 14 self.borderStyle = UITextBorderStyleRoundedRect; 15 //设置键盘的return键 的样式 我们更改为search字样 16 self.returnKeyType = UIReturnKeySearch; 17 //创建imageView对象 18 UIImageView * imgView = [[UIImageView alloc]init]; 19 //设置 imgVIew的用户可交互性 20 imgView.userInteractionEnabled = YES; 21 //给 imgView赋值 tabbar_discover是一个放大镜图片 22 imgView.image = [UIImage imageNamed:@"tabbar_discover"]; 23 //设置self (textField)的 rightView属性和 rightViewMode的属性 24 self.rightView = imgView; 25 self.rightViewMode = UITextFieldViewModeAlways; 26 //向 这张图片添加一个手势 27 UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(btnClick:)]; 28 [imgView addGestureRecognizer:tap]; 29 30 31 } 32 //实现按钮点击事件 33 -(void)btnClick:(UIButton *)btn 34 { 35 NSLog(@" 111111111111%@",self.text); 36 NSLog(@"5555"); 37 }
3,在viewController.m里面 实现 首先记得导入头文件呦!
1 #import "ViewController.h" 2 #import "searchView.h" 3 4 @interface ViewController ()<UITextFieldDelegate> 5 { 6 searchView * search; 7 } 8 @end 9 10 @implementation ViewController 11 12 - (void)viewDidLoad { 13 [super viewDidLoad]; 14 15 search = [[searchView alloc]initWithFrame:CGRectMake(20, 20, 280, 40)]; 16 search.delegate = self; 17 search.layer.cornerRadius = 20; 18 search.clipsToBounds = YES; 19 [self.view addSubview:search]; 20 21 22 } 23 - (BOOL)textFieldShouldReturn:(UITextField *)textField 24 { 25 NSLog(@"%@",search.text); 26 return YES; 27 }
这样就行了 我们来看一下运行效果图
这样是不是达到你想要的效果了??嘿嘿
标签:
原文地址:http://www.cnblogs.com/JustForHappy/p/4911670.html