iOS13中UISegmentedControl选中与高亮状态颜色配置问题
解决UISegmentedControl选中且高亮状态的文本颜色问题
我懂你遇到的困扰——点击已经选中的Segment时,文本颜色莫名变成了白色,完全不是你设置的黑色。这是因为UISegmentedControl对UIControlStateSelected|UIControlStateHighlighted这个组合状态的渲染逻辑有特殊优先级,直接设置的属性会被系统默认逻辑覆盖。
下面给你两种靠谱的解决方案:
方案一:用自定义背景图替代selectedSegmentTintColor
放弃使用setSelectedSegmentTintColor:,转而通过自定义背景图掌控选中状态的外观,这样就能完全控制所有状态下的文本颜色:
// 生成纯色背景图的工具方法 - (UIImage *)imageWithColor:(UIColor *)color { CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f); UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } // 配置SegmentControl - (void)setupSegmentControl { UIColor *tintColor = [UIColor yourCustomTintColor]; // 替换成你的自定义色调色 // 设置各状态的背景图 [self setBackgroundImage:[self imageWithColor:[UIColor clearColor]] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault]; [self setBackgroundImage:[self imageWithColor:tintColor] forState:UIControlStateSelected barMetrics:UIBarMetricsDefault]; [self setBackgroundImage:[self imageWithColor:tintColor] forState:UIControlStateSelected|UIControlStateHighlighted barMetrics:UIBarMetricsDefault]; // 设置各状态的文本颜色 [self setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]} forState:UIControlStateSelected]; [self setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]} forState:UIControlStateSelected|UIControlStateHighlighted]; [self setTitleTextAttributes:@{NSForegroundColorAttributeName: tintColor} forState:UIControlStateNormal]; }
方案二:子类化UISegmentedControl重写属性获取逻辑
如果不想替换背景图,可以通过子类化的方式,强制系统在组合状态下使用你指定的文本颜色:
@interface CustomSegmentControl : UISegmentedControl @end @implementation CustomSegmentControl - (NSDictionary<NSAttributedStringKey,id> *)titleTextAttributesForState:(UIControlState)state { NSDictionary *attributes = [super titleTextAttributesForState:state]; // 当处于选中且高亮状态时,强制替换文本颜色 if ((state & UIControlStateSelected) && (state & UIControlStateHighlighted)) { NSMutableDictionary *mutableAttrs = [attributes mutableCopy]; mutableAttrs[NSForegroundColorAttributeName] = [UIColor blackColor]; return mutableAttrs; } return attributes; } @end
把原生的UISegmentedControl换成这个子类,再搭配你原来的配置代码,就能解决点击选中项时文本变白的问题。
另外要注意:设置状态属性的顺序很关键,一定要把更具体的组合状态设置在单一状态之后,这样系统才会优先使用组合状态的配置。
内容的提问来源于stack exchange,提问作者Ferran Negre
相关产品推荐
相关产品推荐

