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

iOS 13深色模式下如何修改搜索栏左侧图标颜色?

iOS 13深色模式下修改搜索栏左侧图标颜色的解决方案

问题分析

你之前的代码仅修改了搜索栏背景、占位符文本样式,并未针对左侧图标做针对性处理——设置searchBar.backgroundImage会替换整个搜索栏的背景,而非左侧图标,因此无法实现图标颜色修改的需求。

解决方案

以下两种方案可实现深色模式下的图标颜色适配:

1. 修改系统默认放大镜图标颜色

系统搜索栏的左侧图标属于内部searchTextField的leftView,通过设置其tintColor即可修改颜色,结合动态颜色可自动适配深浅模式:

if #available(iOS 13.0, *) {
    guard let searchTextField = searchBar.searchTextField else { return }
    // 动态设置图标颜色:深色模式下为白色,浅色模式下为深灰
    searchTextField.leftView?.tintColor = UIColor { traitCollection in
        traitCollection.userInterfaceStyle == .dark ? .white : .darkGray
    }
}

2. 替换为自定义图标并适配颜色

如果需要使用自定义图标,需替换searchTextField的leftView,并将图标设为模板模式以支持tintColor控制:

if #available(iOS 13.0, *) {
    guard let searchTextField = searchBar.searchTextField else { return }
    
    // 加载自定义图标并设置为模板模式
    let customIcon = UIImage(named: "magnifyingglass")?.withRenderingMode(.alwaysTemplate)
    let iconView = UIImageView(image: customIcon)
    // 适配深浅模式的图标颜色
    iconView.tintColor = UIColor { traitCollection in
        traitCollection.userInterfaceStyle == .dark ? .white : .darkGray
    }
    // 设置图标尺寸与系统默认对齐
    iconView.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
    iconView.contentMode = .scaleAspectFit
    
    // 替换左侧视图并设置显示模式
    searchTextField.leftView = iconView
    searchTextField.leftViewMode = .always
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 09:06:17