更改UISegmentedControl的文本颜色

iAp*_*per 10 xcode objective-c

作为目标c的新手,需要在UIsegmentControl中更改所选段的文本颜色.使用以下代码.

 [[UIsegmentControl.subviews objectAtIndex:segment.selectedSegmentIndex] setTintColor:[UIColor redColor]];
Run Code Online (Sandbox Code Playgroud)

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

Har*_*ngh 39

无法设置所选分段标题的自定义颜色UISegmentedControl.的UIControlStateforState:用于设置文本段的正常和选择状态的属性.

从您的代码:

[[UIsegmentControl.subviews objectAtIndex:segment.selectedSegmentIndex] setTintColor:[UIColor redColor]];
Run Code Online (Sandbox Code Playgroud)

试试此代码:

[segmnt_cntrl setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Arial" size:16.0],
                                                          NSForegroundColorAttributeName:[UIColor redColor],
                                                          NSShadowAttributeName:shadow}
                                                         forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

将segmnt_cntrl替换为Segment Cotrol的对象.试试这个,它可以帮助你实现你的全部目标.

谢谢

  • 除了你的第一段,这个答案是正确的.`forState:`中的`UIControlState`可用于设置普通和选定段文本的属性. (3认同)

i--*_*i-- 18

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

[[UISegmentedControl appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor colorBlack]} forState:UIControlStateSelected];
Run Code Online (Sandbox Code Playgroud)


Bab*_*kar 6

引用@ i--答案

更新了Swift 4.1

UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .selected)
Run Code Online (Sandbox Code Playgroud)

Swift 3.1

UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.red], for: .selected)
Run Code Online (Sandbox Code Playgroud)

对于早期的Swift版本:

UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red as Any], for: .selected)
Run Code Online (Sandbox Code Playgroud)