UIKit分段控件UISegmentedControl背景色仅红色生效问题求助
UISegmentedControl仅红色背景生效,其他颜色无效果的解决方案
问题原因
iOS 13及以上版本中,UISegmentedControl默认采用系统视觉样式,直接设置backgroundColor会被系统自带的半透明背景蒙版覆盖。高饱和度颜色(如红色)能透过蒙版显示,而浅色、低饱和度颜色(如白色)会被完全遮挡,导致设置无效。
解决方案
以下几种方法可以解决该问题,根据你的需求选择:
方法1:清除系统默认背景效果后设置纯色背景
直接移除系统的背景和分割线效果,再设置自定义背景色:
// 先清除系统默认背景 segmentedControl.setBackgroundImage(UIImage(), for: .normal, barMetrics: .default) segmentedControl.setBackgroundImage(UIImage(), for: .selected, barMetrics: .default) segmentedControl.setDividerImage(UIImage(), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default) // 设置白色背景 segmentedControl.backgroundColor = .white // 调整文字颜色避免冲突 segmentedControl.setTitleTextAttributes([.foregroundColor: UIColor.black], for: .normal) segmentedControl.setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected) // 设置选中段的背景色 segmentedControl.selectedSegmentTintColor = .darkGray
方法2:自定义背景图片(支持圆角等样式)
如果需要带圆角或特殊样式的背景,可以生成纯色图片作为背景:
// 生成纯色图片的工具方法 func solidColorImage(color: UIColor, size: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale) color.setFill() UIRectFill(CGRect(origin: .zero, size: size)) let image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage() UIGraphicsEndImageContext() return image } // 应用到分段控件 let bgSize = CGSize(width: 1, height: segmentedControl.frame.height) segmentedControl.setBackgroundImage(solidColorImage(color: .white, size: bgSize), for: .normal, barMetrics: .default) // 设置分割线 segmentedControl.setDividerImage(solidColorImage(color: .lightGray, size: CGSize(width: 1, height: bgSize.height)), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default) // 设置选中段样式 segmentedControl.selectedSegmentTintColor = .lightGray
方法3:全局统一设置(适用于整个APP)
如果需要所有分段控件都使用相同样式,可在AppDelegate或SceneDelegate中全局配置:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 全局设置分段控件样式 let segmentedAppearance = UISegmentedControl.appearance() segmentedAppearance.setBackgroundImage(UIImage(), for: .normal, barMetrics: .default) segmentedAppearance.backgroundColor = .white segmentedAppearance.selectedSegmentTintColor = .blue segmentedAppearance.setTitleTextAttributes([.foregroundColor: UIColor.black], for: .normal) segmentedAppearance.setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected) return true }
注意事项
- 上述方法适配iOS 13及以上版本;iOS 12及以下版本可直接设置
backgroundColor生效。 - 设置背景后务必调整文字颜色,避免因背景与文字颜色相近导致内容不可见。
内容的提问来源于stack exchange,提问作者Fábio Galante
相关产品推荐
相关产品推荐

