UI控件笔记(十五):UI之自定义搜索框的封装

一、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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值