美文网首页
关于searchBar的自定义

关于searchBar的自定义

作者: 心底碎片 | 来源:发表于2016-08-13 15:57 被阅读170次

    最近在项目中遇到需要自定义搜索框的问题,试了很多方法,今天才总算解决了,积累经验,总结一番。
    比如这种样式

    屏幕快照 2016-08-13 下午3.56.23.png

    代码如下

    - (void)createSearchBar{
        searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake((self.view.frame.size.width-300)/2, 100, 300, 40)];
        searchBar.delegate = self;
        searchBar.placeholder = [NSString stringWithCString:"搜索" encoding:NSUTF8StringEncoding];
        //设置searchBar的背景色
        UIImage * searchBarBg1 = [self GetImageWithColor:[UIColor whiteColor] andHeight:40];
        [searchBar setBackgroundImage:searchBarBg1];
        [searchBar setBackgroundColor:[UIColor clearColor]];
        //设置输入框的背景色
        UIImage * searchBarBg2 = [self GetImageWithColor:[UIColor greenColor] andHeight:40];
        [searchBar setSearchFieldBackgroundImage:searchBarBg2 forState:UIControlStateNormal];
        //设置字体颜色/大小,和圆角边框
        UITextField *searchField = [searchBar valueForKey:@"_searchField"];
        searchField.textColor = [UIColor grayColor];
        [searchField setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];
        searchField.font = [UIFont systemFontOfSize:17];
        searchField.layer.cornerRadius = searchBar.frame.size.height/2;
        searchField.layer.masksToBounds = YES;
        [searchBar setContentMode:UIViewContentModeLeft];
        [self.view addSubview:searchBar];
        
    }
    //生成图片
    - (UIImage*) GetImageWithColor:(UIColor*)color andHeight:(CGFloat)height
    {
        CGRect r= CGRectMake(0.0f, 0.0f, 1.0f, height);
        UIGraphicsBeginImageContext(r.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        
        CGContextSetFillColorWithColor(context, [color CGColor]);
        CGContextFillRect(context, r);
        
        UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        return img;
    }
    

    相关文章

      网友评论

          本文标题:关于searchBar的自定义

          本文链接:https://www.haomeiwen.com/subject/fuzesttx.html