0

我正在使用下面的代码在我的分段控件中设置文本颜色。但是,它似乎不起作用。我在这里错过了什么吗?

// Set up segment control
NSArray *itemArray = [NSArray arrayWithObjects: @"Popular", @"Starred", nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
segmentedControl.frame = CGRectMake(40, 200, 220, 20);
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.selectedSegmentIndex = 0;

self.navigationItem.titleView = segmentedControl;

for (id segment in [segmentedControl subviews])
{
    for (id label in [segment subviews])
    {
        if ([label isKindOfClass:[UILabel class]])
        {
            [label setTextAlignment:UITextAlignmentCenter];
            [label setColor:[UIColor blackColor]];
        }
    }           
}

在此处输入图像描述

4

1 回答 1

0

如果您的目标是 iOS 5+,那么您应该这样做:

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                        [UIFont boldSystemFontOfSize:17], UITextAttributeFont,
                        [UIColor blackColor], UITextAttributeTextColor,
                        nil];
[_segmentedControl setTitleTextAttributes:attributes forState:UIControlStateNormal];
NSDictionary *highlightedAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:UITextAttributeTextColor];
[_segmentedControl setTitleTextAttributes:highlightedAttributes forState:UIControlStateHighlighted];
于 2012-12-13T08:16:50.740 回答