我是Objective-C的新手,需要改变UIsegmentControl中选定分段的文本颜色。使用了以下代码。
[[UIsegmentControl.subviews objectAtIndex:segment.selectedSegmentIndex] setTintColor:[UIColor redColor]];
它改变了区块的颜色。请帮帮我。
我是Objective-C的新手,需要改变UIsegmentControl中选定分段的文本颜色。使用了以下代码。
[[UIsegmentControl.subviews objectAtIndex:segment.selectedSegmentIndex] setTintColor:[UIColor redColor]];
它改变了区块的颜色。请帮帮我。
在 UISegmentedControl
中,没有办法设置选定段标题的自定义颜色。在 forState:
中使用的 UIControlState
用于设置正常状态和选定状态下的段文本属性。
从你的代码中:
[[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];
用你的Segment Control对象替换segmnt_cntrl。尝试一下,这可能会帮助你实现整体目标。
谢谢
forState:
中的 UIControlState
可以用于设置正常和选定分段文本的属性。 - jrturton如果您需要更改iOS 7中突出显示段落的文本颜色,这里有一个解决方案(花费了我一些时间才找到,但感谢这篇帖子):
[[UISegmentedControl appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor colorBlack]} forState:UIControlStateSelected];
UIControlStateSelected
替换为UIControlStateNormal
(或者如果需要的话,替换为UIControlStateHighlighted
)的问题。 - i--涉及 @i-- Answer 的引用
更新的 Swift 5
UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .selected)
更新了 Swift 4.1
UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.red], for: .selected)
Swift 3.1
UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red as Any], for: .selected)
对于早期的 Swift 版本:
UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red], for: .selected)
UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected)
- SravanUISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected)
在这里提供另一种解决方案。没有标准的API可以设置UISegmentedControl中单个分段的文本属性。您可以采用不推荐的方法,深入分段控件的视图层次结构中,找到所需的UILabel(如果有)并设置该标签的属性。更好的方法是寻找(或编写)一个自定义控件来模拟UISegmentedControl,并允许以您需要的方式自定义单个分段。
编辑:
实际上,我从错误的角度考虑了这个问题。我的答案基于尝试为特定分段索引设置属性。但事实上,可以通过设置UIControlStateSelected
状态的文本属性来实现此目的。对于造成的困扰,表示抱歉。
Objective 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];
针对Swift 3更新@Babul Prabhakar的答案,因为有大约半打微小的变化:
UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red as Any], for: .selected)