UISearchBar 自定义处理

首先通过 KVC 获取到内部的 textField, 然后自定制处理

UITextField *searchField = [searchBar valueForKey:@"searchField"];

  

if (searchField) {

        [searchField setBorderStyle:UITextBorderStyleNone];

        //placeHolder颜色

        [searchField setValue:_placeholderColor forKeyPath:@"_placeholderLabel.textColor"];

        searchField.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);

        searchField.textColor = _textColor;

        

        //字体大小

        [searchField setValue:_placeHolderFont forKeyPath:@"_placeholderLabel.font"];

        searchField.font = _textFont;

 

        UIImage *image = _leftImage;

        UIImageView *leftImg = [[UIImageView alloc] initWithImage:image];

        leftImg.frame = CGRectMake(0,0,image.size.width, image.size.height);

        searchField.leftView = leftImg;

    }

 

 

其他: 添加圆角(放在一个有圆角的 bgView上面)

 

 UIView *bg = [[UIView alloc]initWithFrame:CGRectMake(2022030030)];

    bg.backgroundColor = [UIColor whiteColor];

    [self.view addSubview:bg];

    bg.layer.cornerRadius = 15;

    bg.layer.masksToBounds = YES;

    

    UISearchBar *bar = [[UISearchBar alloc]initWithFrame: bg.bounds];

    [bg addSubview:bar];

    bar.placeholder = @"搜索...";

    [bar setBackgroundImage:[UIImage imageNamed:@"clearImage@2x"]];

 

修改圆角大小

首先在 UIView 的 category 里加一个方法:
- (UIView*)subViewOfClassName:(NSString*)className { for (UIView* subView in self.subviews) { if ([NSStringFromClass(subView.class) isEqualToString:className]) { return subView; } UIView* resultFound = [subView subViewOfClassName:className]; if (resultFound) { return resultFound; } } return nil; }

用的时候:
UIView* backgroundView = [searchBar subViewOfClassName:@"_UISearchBarSearchFieldBackgroundView"];
backgroundView.layer.cornerRadius = 14.0f;
backgroundView.clipsToBounds = YES;
用这个方法还可以改取消按钮的颜色、字体什么的。


 

posted @ 2017-11-14 16:22  Da雪山  阅读(1355)  评论(1编辑  收藏  举报