You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift4中如何设置Scope Bar颜色及隐藏搜索栏图标?

嘿,针对你在Swift 4开发中遇到的这两个UISearchBar问题,我整理了可直接复用的解决方法,一起来看看:

1. 设置UISearchBar的Scope Bar颜色

Scope Bar本质是UISegmentedControl,我们需要先定位到这个控件,再分别配置背景色、按钮文字的选中/未选中状态颜色:

  • 先遍历搜索栏的子视图,找到UISegmentedControl实例
  • 自定义背景色、文字颜色,还可以添加边框效果来呼应主题

直接把这段代码加到你的searchBarSetup函数里就行:

// 配置Scope Bar颜色
if let scopeBar = searchBar.subviews.first?.subviews.compactMap({ $0 as? UISegmentedControl }).first {
    let darkRed = UIColor(red: 0.392, green: 0.012, blue: 0.020, alpha: 1.00)
    // 设置Scope Bar背景色(这里用浅灰色示例,你可以换成自己需要的颜色)
    scopeBar.backgroundColor = UIColor.lightGray
    // 未选中状态的文字颜色
    scopeBar.setTitleTextAttributes([.foregroundColor: UIColor.black], for: .normal)
    // 选中状态的文字颜色(和你的tintColor保持一致)
    scopeBar.setTitleTextAttributes([.foregroundColor: darkRed], for: .selected)
    // 可选:给Scope Bar加边框,和主题色呼应
    scopeBar.layer.borderColor = darkRed.cgColor
    scopeBar.layer.borderWidth = 1.0
}
2. 隐藏搜索栏中的图标

搜索栏的左侧图标是内部UITextField的leftView,我们可以通过KVC获取到这个文本框,然后隐藏或移除它,同时调整文字内边距避免显示错位:

  • 用value(forKey: "searchField")获取搜索栏的文本框
  • 隐藏leftView或者直接设置为nil,再关闭leftView的自动显示模式

代码示例:

// 隐藏搜索栏左侧图标
if let searchTextField = searchBar.value(forKey: "searchField") as? UITextField {
    // 方法一:隐藏图标
    searchTextField.leftView?.isHidden = true
    // 方法二:彻底移除图标(二选一即可)
    // searchTextField.leftView = nil
    // 关闭leftView的显示模式,避免系统自动恢复
    searchTextField.leftViewMode = .never
    // 调整文字内边距,让搜索文字不贴左边,提升美观度
    searchTextField.textInsets = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 0)
}

最后,整合后的完整searchBarSetup函数是这样的:

func searchBarSetup() {
    searchBar.showsScopeBar = true
    searchBar.scopeButtonTitles = ["Name","Effect","Component"]
    searchBar.selectedScopeButtonIndex = 0
    searchBar.delegate = self
    searchBar.showsCancelButton = false
    let darkRed = UIColor(red: 0.392, green: 0.012, blue: 0.020, alpha: 1.00)
    searchBar.tintColor = darkRed
    self.navigationItem.titleView = searchBar
    
    // 配置Scope Bar颜色
    if let scopeBar = searchBar.subviews.first?.subviews.compactMap({ $0 as? UISegmentedControl }).first {
        scopeBar.backgroundColor = UIColor.lightGray
        scopeBar.setTitleTextAttributes([.foregroundColor: UIColor.black], for: .normal)
        scopeBar.setTitleTextAttributes([.foregroundColor: darkRed], for: .selected)
        scopeBar.layer.borderColor = darkRed.cgColor
        scopeBar.layer.borderWidth = 1.0
    }
    
    // 隐藏搜索栏图标
    if let searchTextField = searchBar.value(forKey: "searchField") as? UITextField {
        searchTextField.leftView?.isHidden = true
        searchTextField.leftViewMode = .never
        searchTextField.textInsets = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 0)
    }
}

内容的提问来源于stack exchange,提问作者JIN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:15:52