如何更改UISegmentedControl的字体颜色

90

我试图将 iOS 4.* 中的 UISegmentedControl 字体颜色从白色更改为黑色。

UISegmentedControl *button = [[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:itemTitle, nil]] autorelease];
button.momentary = YES;
button.segmentedControlStyle = UISegmentedControlStyleBar;
button.tintColor = [UIColor redColor];      
for (id segment in [button subviews]) {
    for (id label in [segment subviews]) {
        if ([label isKindOfClass:[UILabel class]]) {
            UILabel *titleLabel = (UILabel *) label;
            [titleLabel setTextColor:[UIColor blackColor]];
        }
    }
}
UIBarButtonItem *barButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];

但是文本颜色没有改变。我应该怎么做才能改变UISegmentedControl的文本颜色?

12个回答

132
在iOS 6.0及以上版本中,这非常简单:
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                            [UIFont boldSystemFontOfSize:17], NSFontAttributeName,
                            [UIColor blackColor], NSForegroundColorAttributeName,
                            nil];
[_segmentedControl setTitleTextAttributes:attributes forState:UIControlStateNormal];
NSDictionary *highlightedAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
[_segmentedControl setTitleTextAttributes:highlightedAttributes forState:UIControlStateSelected];

有没有关于更改字体类型的想法? - Vaibhav Saran
[UIFont fontWithName:@"HelveticaNeue" size:17.0f] - pbibergal
有什么想法可能导致这个不起作用吗?作为一个实验,我将文本颜色设置为绿色,但一切仍然是默认值(灰色文本在淡灰色背景上,或者如果高亮则是白色文本在蓝色背景上。这是iOS6。iOS7是默认的白色/透明)。谢谢! - Olie
请参考以下网址中给出的详细说明:http://datacalculation.blogspot.in/2014/10/how-to-change-uisegmentedcontrol-text.html - iOS Test
10
在 iOS 8.1 上进行测试时,此答案的最后一行应从“UIControlStateHighlighted”更改为“UIControlStateSelected”,以实现所需效果。 - eager to learn
单个片段是否可能? - Ofir Malachi

93

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

Objective-C

[[UISegmentedControl appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor blackColor]} forState:UIControlStateSelected];

Swift

  let titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]  
  UISegmentedControl.appearance().setTitleTextAttributes(titleTextAttributes, forState: .Selected)

很好。您可以在http://datacalculation.blogspot.in/2014/10/how-to-change-uisegmentedcontrol-text.html上查看详细信息。 - iOS Test
这个答案最终帮助我完成了我的应用选择按钮的要求,之前包括将分段控件保留在超级UI视图中使边框正方形的方法。 - KoreanXcodeWorker
3
对于Swift 5:var titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] UISegmentedControl.appearance().setTitleTextAttributes(titleTextAttributes, for: .normal) - Eric

84

代码以将两个状态的字体颜色设置为黑色

Swift 5

    let titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black]
    segmentedControl.setTitleTextAttributes(titleTextAttributes, for: .normal)
    segmentedControl.setTitleTextAttributes(titleTextAttributes, for: .selected)

Swift 4

    let titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.black]
    segmentedControl.setTitleTextAttributes(titleTextAttributes, for: .normal)
    segmentedControl.setTitleTextAttributes(titleTextAttributes, for: .selected)

不支持iOS 13和Swift 5,Xcode无法再识别“segmentedControl”。 - Sky
1
@Sky,今天在我的应用程序的segmentedControl上添加了一些错误修复,这个解决方案适用于iOS 13.2和Swift5。 - Zhou Haibo

31

以下是将字体设置为粗体和字号的代码:

UIFont *Boldfont = [UIFont boldSystemFontOfSize:12.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:Boldfont
                                                       forKey: NSFontAttributeName];
[segmentedControl setTitleTextAttributes:attributes 
                                forState:UIControlStateNormal];

希望它有所帮助


5
注意:本回答需要 iOS 5 及以上版本。 - Costique
1
这个答案并没有像主题发起人要求的那样更改字体颜色,只更改了字体大小。pbibergal的回答更完整。 - Terrabythia
这个可以运行,但是会出现警告,因为UITextAttributeFont已经被弃用了。应该使用“NSFontAttributeName”代替。感谢https://dev59.com/XHE95IYBdhLWcg3whOLK上的@johngraham。 - mavericks

21

更新至iOS 14和Swift 5:

extension UISegmentedControl
{
    func defaultConfiguration(font: UIFont = UIFont.systemFont(ofSize: 12), color: UIColor = UIColor.white)
    {
        let defaultAttributes = [
            NSAttributedString.Key.font: font,
            NSAttributedString.Key.foregroundColor: color
        ]
        setTitleTextAttributes(defaultAttributes, for: .normal)
    }

    func selectedConfiguration(font: UIFont = UIFont.boldSystemFont(ofSize: 12), color: UIColor = UIColor.red)
    {
        let selectedAttributes = [
            NSAttributedString.Key.font: font,
            NSAttributedString.Key.foregroundColor: color
        ]
        setTitleTextAttributes(selectedAttributes, for: .selected)
    }
}

已更新至Swift 4 - 使用这个扩展(因为扩展总是很棒..!!)

extension UISegmentedControl {

func defaultConfiguration(font: UIFont = UIFont.systemFont(ofSize: 12), color: UIColor = UIColor.gray) {
    let defaultAttributes = [
        NSAttributedStringKey.font.rawValue: font,
        NSAttributedStringKey.foregroundColor.rawValue: color
    ]
    setTitleTextAttributes(defaultAttributes, for: .normal)
}

func selectedConfiguration(font: UIFont = UIFont.boldSystemFont(ofSize: 12), color: UIColor = UIColor.red) {
    let selectedAttributes = [
        NSAttributedStringKey.font.rawValue: font,
        NSAttributedStringKey.foregroundColor.rawValue: color
    ]
    setTitleTextAttributes(selectedAttributes, for: .selected)
}
}

从各自的类中,您可以使用这些函数:

@IBOutlet weak var segment: UISegmentedControl!

segment.defaultConfiguration()
// or provide paramater as per your requirement
segment.selectedConfiguration(color: .blue)

7

Swift 5扩展

extension UISegmentedControl {

    func setTitleColor(_ color: UIColor, state: UIControl.State = .normal) {
        var attributes = self.titleTextAttributes(for: state) ?? [:]
        attributes[.foregroundColor] = color
        self.setTitleTextAttributes(attributes, for: state)
    }
    
    func setTitleFont(_ font: UIFont, state: UIControl.State = .normal) {
        var attributes = self.titleTextAttributes(for: state) ?? [:]
        attributes[.font] = font
        self.setTitleTextAttributes(attributes, for: state)
    }

}

正常工作。谢谢。 - thevikasnayak

7

在Swift 5中,您可以使用以下语法更改颜色

Swift 5

let titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.red]
groupSegment.setTitleTextAttributes(titleTextAttributes, for: .selected)

6
for (UIView *v in [[[segment subviews] objectAtIndex:0] subviews]) {
    if ([v isKindOfClass:[UILabel class]]) {
        UILabel *label=(UILabel *)[v retain];
        lable.textColor=[UIColor blackColor];
    }
}

适用于iOS 3.0及以上版本


7
警告:您不应该保留该标签。 - Costique

5

为了帮助那些正在使用Swift的人,我会提供两种可能的方法。您可以在UIAppearance中更改文本属性,也可以直接在您正在使用的分段控件中进行更改。

第一个例子是在外观中设置属性,这样您将自定义应用程序中所有的分段控件:

    let attributes = [ NSForegroundColorAttributeName : UIColor.grayColor(),
        NSFontAttributeName : UIFont.systemFontOfSize(20)];
    let attributesSelected = [ NSForegroundColorAttributeName : UIColor.blueColor(),
        NSFontAttributeName : UIFont.systemFontOfSize(20)];
    UISegmentedControl.appearance().setTitleTextAttributes(attributes, forState: UIControlState.Normal)
    UISegmentedControl.appearance().setTitleTextAttributes(attributesSelected, forState: UIControlState.Selected)

第二个例子,直接在分段中,将仅自定义此分段:
    let attributes = [ NSForegroundColorAttributeName : UIColor.grayColor(),
        NSFontAttributeName : UIFont.systemFontOfSize(20)];
    let attributesSelected = [ NSForegroundColorAttributeName : UIColor.blueColor(),
        NSFontAttributeName : UIFont.systemFontOfSize(20)];
    segmented.setTitleTextAttributes(attributes, forState: UIControlState.Normal)
    segmented.setTitleTextAttributes(attributesSelected, forState: UIControlState.Selected)

4

Swift 3.2:

let attributes = [
                          NSFontAttributeName : bigTextFont,
                          NSForegroundColorAttributeName : UIColor.blue,
                          ]         
segmentedControl?.setTitleTextAttributes(attributes, for: .normal)

注意:如果您使用自定义背景颜色,您会在角落看到一个故障(颜色将填充到段外..),因此请使用以下行来剪辑它:

segmentedControl!.layer.cornerRadius = 4.0
segmentedControl!.clipsToBounds = true

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接