14

我是目标 c 的新手,需要更改 UIsegmentControl 中选定段的文本颜色。使用以下代码。

 [[UIsegmentControl.subviews objectAtIndex:segment.selectedSegmentIndex] setTintColor:[UIColor redColor]];

它改变了段颜色。请帮帮我..

4

7 回答 7

41

无法在UISegmentedControl. UIControlStateinforState:用于设置正常和选中状态的段文本的属性。

从您的代码:

[[UIsegmentControl.subviews objectAtIndex:segment.selectedSegmentIndex] setTintColor:[UIColor redColor]];

试试这个代码:

[segmnt_cntrl setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Arial" size:16.0],
                                                          NSForegroundColorAttributeName:[UIColor redColor],
                                                          NSShadowAttributeName:shadow}
                                                         forState:UIControlStateNormal];

将 segmnt_cntrl 替换为您的 Segment Cotrol 对象。试试这个,它可能会帮助你实现你的总体目标。

谢谢

于 2012-10-27T06:16:16.407 回答
21

如果您需要更改 iOS 7 中突出显示部分的文本颜色,这里有一个解决方案(我花了一段时间才找到,但感谢这篇文章):

[[UISegmentedControl appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor colorBlack]} forState:UIControlStateSelected];
于 2014-01-31T16:16:03.737 回答
11

参考@i--答案

更新了 Swift 5

UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .selected)

更新 Swift 4.1

UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.red], for: .selected)

斯威夫特 3.1

UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red as Any], for: .selected)

对于早期的 Swift 版本:

UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red], for: .selected)
于 2016-08-06T18:35:32.843 回答
4

除了@Babl Prabhakar 的回答

斯威夫特 5: UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected)

于 2019-04-07T19:48:04.027 回答
2

没有标准 API 可以在 UISegmentedControl 中设置单个段的文本属性。您可以采用不推荐的方法来挖掘分段控件的视图层次结构,找到所需的 UILabel(如果有)并设置该标签的属性。更好的方法是找到(或编写)模拟 UISegmentedControl 并允许以您需要的方式自定义单个段的自定义控件。

编辑:

实际上,我是从错误的角度看待这个问题的。我的回答是基于尝试为特定段索引设置属性。但实际上这可以通过设置UIControlStateSelected状态的文本属性来实现。对困惑感到抱歉。

于 2012-10-27T05:06:52.560 回答
1

目标 C

设置字体样式、大小和颜色

NSDictionary *attributes = [NSDictionary dictionaryWithObject: [UIFont fontWithName: @"Arial" size:16] forKey:NSFontAttributeName];
[self->mySegmentControl setTitleTextAttributes: attributes forState: normal];
[self->mySegmentControl setTitleTextAttributes: @{NSForegroundColorAttributeName: UIColor.blueColor} forState: UIControlStateSelected];
于 2020-05-20T13:09:06.087 回答
0

更新了@Babul Prabhakar 对 Swift 3 的回答,因为大约有六个小事情发生了变化:

UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red as Any], for: .selected)
于 2017-03-04T19:18:21.857 回答