搜索框 searchbar

1.遵守代理

  • (UISearchBar *)searchBar
    {
    if (_searchBar == nil) {
    _searchBar = [[UISearchBar alloc]init];
    [_searchBar setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHex:0xeaeaea]]];//背景图片
    [_searchBar sizeToFit];
    [_searchBar changeLeftPlaceholder:@"女装"];
    [_searchBar setDelegate:self];
    [_searchBar setKeyboardType:UIKeyboardTypeDefault];
    [_searchBar setTranslucent:YES];//设置是否透明
    [_searchBar setSearchBarStyle:UISearchBarStyleProminent];
    [_searchBar setShowsCancelButton:NO];
    _searchBar.tintColor = [UIColor orangeColor];
    UITextField *txfSearchField = [_searchBar valueForKey:@"_searchField"];
    if (txfSearchField) {
    UIImageView *searchImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, 15)];
    searchImageView.image = [UIImage imageNamed:@"icon_search"];
    txfSearchField.backgroundColor=[UIColor colorWithHex:0xeaeaea];
    searchImageView.contentMode = UIViewContentModeCenter;
    txfSearchField.leftView = searchImageView;
    txfSearchField.leftViewMode = UITextFieldViewModeAlways;
    }
    }
    [self addSubview:_searchBar];
    [_searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(@7);
    make.left.equalTo(@2);
    make.height.equalTo(@30);
    make.right.equalTo(@-2);
    }];
    return _searchBar;
    }
    3.设置搜索框取消按钮

  • (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
    {
    searchBar.showsCancelButton = YES; //显示“取消”按钮
    for(id cc in [searchBar subviews])
    {
    for (UIView *view in [cc subviews]) {
    if ([NSStringFromClass(view.class)isEqualToString:@"UINavigationButton"])
    {
    UIButton *btn = (UIButton *)view;
    [btn setTitle:@"取消" forState:UIControlStateNormal];
    }
    }
    }
    }
    4.搜索框响应键盘 return事件代理方法

  • (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"确定事件");
    if (searchBar.text.length) {
    NSLog(@"弹出搜索试图");
    [self finder:searchBar.text];
    }else{
    [self.dateSource removeAllObjects];
    [self updateTabelFrame];
    [self.firendtableview reloadData];
    }
    }
    5.搜索框监听输入内容变化

  • (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"确定事件");
    if (searchBar.text.length) {
    NSLog(@"弹出搜索试图");
    [self finder:searchBar.text];
    }else{
    [self.dateSource removeAllObjects];
    [self updateTabelFrame];
    [self.firendtableview reloadData];
    }
    }

你可能感兴趣的:(搜索框 searchbar)