2012-12-13 58 views
0

我正在使用下面的代碼來設置我的分段控件中的文本顏色。但是,它似乎並不奏效。我在這裏錯過了什麼嗎?無法更改segmentedControl中的字體顏色

// 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]]; 
     } 
    }   
} 

enter image description here

回答

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