UISearchBar基本用法及searchBar常用代理方法

直接上代码。

1.初始化


UISearchBar *searchBar = [[UISearchBaralloc]initWithFrame:CGRectMake(0,0, 320,40)];

    searchBar.placeholder =@"搜索"; //和textfield一样有placeholder属性

    searchBar.delegate =self;

    [self.viewaddSubview:searchBar];

//由于个人需求 需要使用圆角的搜索框所以顺便对searchBar进行了一次遍历取出textfiled(ps:如果想修改searchBar背景 可以用imgaeView去接收view)

for (UIView *viewin searchBar.subviews) {

       if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {

         _textfield = [view.subviewsobjectAtIndex:1];

           _textfield.layer.cornerRadius =14;

           _textfield.layer.masksToBounds =YES;

        }

    }



2.代理方法 需要引入:< UISearchBarDelegate>

#pragma mark 输入内容就会触发

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText

{

   NSLog(@"1");

}

#pragma mark 点击搜索栏中的textFiled触发

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar

{

    _textfield.placeholder =@"输入书名/作者";

    //弹出键盘的一瞬间 给背景加了一层灰色蒙版,用于点击回首键盘。

    _buttonBackground = [MyButtonmakeButtonFrame:CGRectMake(0,40, 320, 568 -40) withButtonBackGroundColor:[UIColorcolorWithWhite:0.1alpha:0.1]withButtonBackImageName:nilwithButtonTitle:nilwithButtonTitleColor:nilwithButtonTitleFont:nil];

    [_buttonBackgroundaddTarget:selfaction:@selector(buttonSearch)forControlEvents:UIControlEventTouchUpInside];

        [self.viewaddSubview:_buttonBackground];

}


#pragma mark 点击search跳到搜索结果页

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar

{

    CartoonSearchViewController *vc = [[CartoonSearchViewControlleralloc]init];

    [self.navigationControllerpushViewController:vc animated:YES];

}



其实还有很多方法,具体的大家可以参考api文档,列出来的只有3个,个人认为最为常用还是第2个,第3个



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值