如何更改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个回答

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

我正在使用Monotouch。 不知道为什么,但当视图被推送时,文本颜色对我来说没有改变。 为了解决这个问题,我只需将标签添加到段控件的父视图中,然后更改它们的颜色:

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

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