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;
用這個方法還可以改取消按鈕的顏色、字體什么的。


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM