如何更改UISegmentedControl的字体颜色

时间:2012-01-27 06:32:09

标签: iphone objective-c cocoa-touch uisegmentedcontrol

我尝试将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的文字颜色?

12 个答案:

答案 0 :(得分:117)

在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];

答案 1 :(得分:64)

如果你需要更改iOS 7中突出显示的片段的文字颜色,这里有一个解决方案(花了我一段时间才找到,但是thanks to this post):

<强>目标C

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

<强>夫特

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

答案 2 :(得分:29)

以下是将字体设置为粗体和点大小的代码:

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

我希望它有所帮助

答案 3 :(得分:12)

Swift 4代码将状态字体颜色设置为黑色

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

答案 4 :(得分:7)

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及以上版本

答案 5 :(得分:4)

以防万一到达那里,并使用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)

答案 6 :(得分:4)

swift 3.2:

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

注意:如果您使用自定义背景颜色,您将在角落中看到一个小故障(颜色将填充外部区段..),因此请使用这些线条将其剪切:

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

答案 7 :(得分:4)

更新了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)

答案 8 :(得分: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)
    }

}

答案 9 :(得分: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类参考的Customizing Appearance部分找到所有可能的简单自定义。

答案 10 :(得分:1)

我正在使用monotouch。 不知道为什么,但是当推送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);

答案 11 :(得分:1)

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

快速5

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