一、SearchBar.h文件
#import <UIKit/UIKit.h>
@protocol SearchBarDelegate <NSObject>//要把当前搜索View里的搜索内容传给VC
-(void)sendTextToVC:(NSString*)text;
@end
@interface SearchBar : UIView<UITextFieldDelegate>
@property(nonatomic,assign)id<SearchBarDelegate>delegate;
@end
二、SearchBar.m文件
#import "SearchBar.h"
#import <QuartzCore/QuartzCore.h>
@implementation SearchBar
-(id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if(self)
{
self.backgroundColor = [UIColor colorWithRed:222/255.0 green:222/255.0 blue:222/255.0 alpha:1];
UITextField *searchBar = [[UITextField alloc] initWithFrame:CGRectMake(10,7,300,30)];
//把一个UI变成圆角的,ios6之前需要添加QuartzCore.framework库
searchBar.layer.masksToBounds = YES;//当前V上面的子视图不会超了
searchBar.layer.cornerRadius = 5;
searchBar.backgroundColor = [UIColor whiteColor];
searchBar.delegate = self;
searchBar.placeholder = @"60万款应用搜索看";
[self addSubview:searchBar];
[searchBar release];
searchBar.tag = 5000;
UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
cancelBtn.frame = CGRectMake(self.frame.size.width-70,7,60,30);
[cancelBtn setTitle:@"cancel" forState:UIControlStateNormal];
[cancelBtn addTarget:self action:@selector(cancelDown) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:cancelBtn];
cancelBtn.tag = 1999;
cancelBtn.hidden = YES;
}
returnself;
}
-(void)cancelDown//取消搜索功能
{
UIButton *cancelBtn = (UIButton*)[self viewWithTag:1999];
cancelBtn.hidden = YES;
UITextField *textField = (UITextField*)[self viewWithTag:5000];
[textField resignFirstResponder];
textField.text = @"";//取消的时候,文本输入框里置空
[UIView animateWithDuration:2 animations:^{
textField.frame = CGRectMake(10,7,300,30);
}];
[self.delegate sendTextToVC:@""];//取消的时候,给vc传一个空字符串,当vc收到空字符串的时候,表示不使用搜索接口,而使用当前VC正常的loadData接口(下拉刷新接口)
}
#pragma mark textfield代理
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
[UIView animateWithDuration:2 animations:^{
textField.frame = CGRectMake(10,7,210,30);
} completion:^(BOOL finished) {
UIButton *cancelBtn = (UIButton*)[self viewWithTag:1999];
cancelBtn.hidden = NO;
}];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField//搜索
{
[textField resignFirstResponder];
[self.delegate sendTextToVC:textField.text];//代理传文本字符串
returnYES;
}
@end