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

如何修改iOS 13中UISegmentedControl未选中分段的文本颜色?

解决UISegmentedControl未选中分段文本颜色修改问题

别担心,其实你用的setTitleTextAttributes(_:for:)方法是完全正确的,只是没找对对应的属性和状态而已。

要把未选中分段的文本改成白色,你只需要针对.normal状态,使用NSAttributedString.Key.foregroundColor这个属性来设置就行,具体代码示例如下:

Swift 版本

// 先初始化你的双分段控制器
let segmentedControl = UISegmentedControl(items: ["选项A", "选项B"])

// 设置未选中状态的文本颜色为白色
segmentedControl.setTitleTextAttributes(
    [.foregroundColor: UIColor.white],
    for: .normal
)

// 可选操作:如果需要调整选中状态的文本颜色,也可以一并设置
segmentedControl.setTitleTextAttributes(
    [.foregroundColor: UIColor.black], // 替换成你想要的选中态颜色
    for: .selected
)

Objective-C 版本

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"选项A", @"选项B"]];

// 设置未选中状态文本为白色
[segmentedControl setTitleTextAttributes:@{
    NSForegroundColorAttributeName: [UIColor whiteColor]
} forState:UIControlStateNormal];

// 可选操作:设置选中状态文本颜色
[segmentedControl setTitleTextAttributes:@{
    NSForegroundColorAttributeName: [UIColor blackColor]
} forState:UIControlStateSelected];

小提醒

  • 一定要在分段控制器初始化完成后再调用这段设置代码(比如放在viewDidLoad方法里),否则配置可能不会生效。
  • 如果你的项目是iOS 13及以上版本,且分段控制器用了系统的.plain样式,要确认没有全局的外观设置覆盖了你这个局部配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 13:37:42