美文网首页
IOS 扁平化且背景透明的搜索框

IOS 扁平化且背景透明的搜索框

作者: tino又想吃肉了 | 来源:发表于2020-08-12 16:57 被阅读0次

前言

我们的目标是获得一个看起来较为“轻快”且能融入白色背景的搜索框。
效果如图


image.png

实现

实现方法其实很简单。

  • 首先,我们获得一个UISearchController实例,并将背景颜色设为clearColor
    UISearchController* search = [[UISearchController alloc] initWithSearchResultsController:nil];
    search.searchResultsUpdater = self;
    search.dimsBackgroundDuringPresentation = false;
    search.searchBar.backgroundColor = [UIColor clearColor];
    search.searchBar.placeholder = @"搜索";
  • 接着,我们取出搜索框边框的UIView,并进行相关属性的设定
    UIView* searchTextField = [[[search.searchBar.subviews firstObject] subviews] lastObject];
    searchTextField.layer.borderWidth = 1;//边框宽度
    searchTextField.layer.borderColor = [UIColor lightGrayColor].CGColor;//边框颜色
    searchTextField.layer.cornerRadius = 10.0f;//边框圆角
  • 此时,如果你不取出搜索框的背景view,边框的效果是这样的
    image.png
    这时,如果你需要使背景变为白色,只需要执行这一段代码
for(UIView* view in search.searchBar.subviews)
    {
        if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {
            [[view.subviews objectAtIndex:0] removeFromSuperview];
            break;
        }
    }
  • 最后,只需要设置搜索框的文字自适应,设置搜索框的代理并添加到view,就可以了。
    [search.searchBar sizeToFit];
    self.search.delegate = self;
    self.tableView.tableHeaderView = search.searchBar;
   //这里我的搜索框是在TableView中使用,实际使用添加到你所需要的view上。

结语

最后我们得到了如文章开头给出的搜索框。实际使用中如果你有其他诸如适配黑暗模式的需求,只需要改变一下background颜色即可。你也可以自定义更多搜索框的属性,如文字、颜色或者是搜索图标。


以上
Tino Wu

相关文章

网友评论

      本文标题:IOS 扁平化且背景透明的搜索框

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