如何更改UISegmentedControl的字体颜色


76

我尝试将字体颜色从白色更改为黑色UISegmentedControl(对于iOS 4. *)

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什么?

Answers:


127

在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


9
测试iOS 8.1中,最后一行这个答案应该改变UIControlStateHighlighted,以UIControlStateSelected达到预期的效果。
渴望

86

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

目标C

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

迅速

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


这个答案终于帮我完成我的应用程序的选择按钮的要求,此前包括保持分段控制在一个超级的UIView的方法,使边境广场....
KoreanXcodeWorker

55

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

迅捷5

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

斯威夫特4

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

适用于iOS 13和斯威夫特5不起作用,Xcode中无法识别segmentedControl
天空

1
@Sky,今天就在我的应用程序的segmentedControl上添加一些错误修复,该解决方案可在iOS 13.2和Swift5上使用。
ChuckZHB

31

下面是将字体设置为粗体和磅值的代码:

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

希望对您有所帮助


4
注意:这个答案需要iOS 5
Costique

1
此答案不会更改主题启动程序要求的字体颜色,而只会更改字体大小。pbibergal的答案更加完整。
Terrabythia

这可行,但是警告不赞成使用UITextAttributeFont。而是使用“ NSFontAttributeName”。多亏了stackoverflow.com/questions/2280391/…的
小牛

12

针对iOS 13更新:

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)

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及更高版本


6
警告:您不应该保留标签。
Costique 2012年

5

以防万一帮助到那里并正在迅速工作的其他人。

我将提出两种可能的方法。您可以在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

迅速3.2:

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

注意:如果使用自定义背景色,则会在角落出现毛刺(颜色将填充外部线段..),因此请使用以下线条对其进行裁剪:

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

4

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

迅捷5

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

4

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)
    }

}

2

在iOS 5.0及更高版本中,您可以使用titleTextAttributes来自定义UISegmentedControl对象:

NSDictionary *segmentedControlTextAttributes = @{NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue" size:18.0], NSForegroundColorAttributeName:[UIColor whiteColor]};
[self.segmentedControl setTitleTextAttributes:segmentedControlTextAttributes forState:UIControlStateNormal];
[self.segmentedControl setTitleTextAttributes:segmentedControlTextAttributes forState:UIControlStateHighlighted];
[self.segmentedControl setTitleTextAttributes:segmentedControlTextAttributes forState:UIControlStateSelected];

在这里,我将字体设置为自定义字体,字体大小,每种状态的颜色UISegmentedControl

您可以在UISegmentedControl类参考的“定制外观”部分中找到所有可能的简单定制。


1

我正在使用单点触控。不知道为什么,但是当我按下View时,文本颜色并没有改变。为了解决这个问题,只需在标签控件超级视图中添加标签,然后更改其颜色即可:

public static void SetColoredTittles(this UISegmentedControl s, string[] titles, UIColor selected, UIColor notSelected)
{ 
    var segmentedLabels = new List<UILabel>();
    float width = s.Frame.Width/titles.Length;

    for (int i = 0; i < titles.Length; i++)
    {
        var frame = new RectangleF(s.Frame.X + i*width, s.Frame.Y, width,s.Frame.Height);
        UILabel label = new UILabel(frame);
        label.TextAlignment = UITextAlignment.Center;
        label.BackgroundColor = UIColor.Clear;
        label.Font = UIFont.BoldSystemFontOfSize(12f);
        label.Text = titles[i];
        s.Superview.AddSubview(label);
        segmentedLabels.Add(label);
    }

    s.ValueChanged += delegate
    {
        TextColorChange(s,segmentedLabels, selected, notSelected);
    };
    TextColorChange(s,segmentedLabels, selected, notSelected);
}

static void TextColorChange(UISegmentedControl s, List<UILabel> segmentedLabels, UIColor selected, UIColor notSelected)
{
    for (int i = 0; i < segmentedLabels.Count; i++)
    {
        if(i == s.SelectedSegment) segmentedLabels[i].TextColor = selected;
        else segmentedLabels[i].TextColor = notSelected;
    }
}

然后用它

segmented.SetColoredTittles(new string[] {
            "text1",
            "text2",
            "text3"
        }, UIColor.White,UIColor.DarkGray);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.