UISearchBar的自定义

UISearchBar是由两个subView组成的,一个是UISearchBarBackGround,另一个是UITextField.
代码中没有直接操作两个subView的属性,要想修改,需要去子控件中修改
一,修改UISearchBar的背景框
删除它的方法有两种:一种是直接将 UISearchBarBackGround移去;另一种是创建一个UIView设置其颜色加载到UISearchBarBaceGround上作为UISearchBar的背景颜色

//获取其子视图
 UIView *subView = _searchBar.subviews[0];
     //1,移除
    for (UIView *view in subView.subviews)
    {
        //搜索背景框
        if ([view isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
        {
            [view removeFromSuperview];
        }
    }
     //2,替换
     UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"40-di.png"]];
[subView insertSubview:imageView atIndex:1];

二,修改其TextField

//获取其子视图
 UIView *subView = _searchBar.subviews[0];
    for (UIView *view in subView.subviews)
    {
        //自定义textField
        if ([view isKindOfClass:[UITextField class]])
        {
            _textField = (UITextField *)view;
            _textField.layer.borderWidth = 0.5;
            _textField.layer.borderColor = H_LINECOLOR.CGColor;
            _textField.layer.cornerRadius = 2;
            _textField.clipsToBounds = YES;
        }
    }

三,代理方法
//输入搜索文字时隐藏搜索按钮,清空时显示

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
searchBar.showsScopeBar = YES;
[searchBar sizeToFit];
[searchBar setShowsCancelButton:YES animated:YES];
return YES;
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
searchBar.showsScopeBar = NO;
[searchBar sizeToFit];
[searchBar setShowsCancelButton:NO animated:YES];
return YES;
}

//改变搜索按钮文字
//改变UISearchBar取消按钮字体

for(id cc in [searchBar subviews])
{
if([cc isKindOfClass:[UIButton class]])
{
UIButton *btn = (UIButton *)cc;
[btn setTitle:@"搜索" forState:UIControlStateNormal];
}

你可能感兴趣的:(oc基础,自定义技巧)