2012-10-27 32 views
8

Iam新增目標c,需要更改UIsegmentControl中選定區段的文本顏色。 使用以下代碼。更改UISegmentedControl的文本顏色

[[UIsegmentControl.subviews objectAtIndex:segment.selectedSegmentIndex] setTintColor:[UIColor redColor]]; 

它改變了段color.Help我請..

回答

38

無法在UISegmentedControl中設置所選片段標題的自定義顏色。 forState:中的UIControlState用於設置正常狀態和選定狀態的段文本屬性。

從代碼:

[[UIsegmentControl.subviews objectAtIndex:segment.selectedSegmentIndex] setTintColor:[UIColor redColor]]; 

試試這個代碼:

[segmnt_cntrl setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Arial" size:16.0], 
                  NSForegroundColorAttributeName:[UIColor redColor], 
                  NSShadowAttributeName:shadow} 
                 forState:UIControlStateNormal]; 

與分段Cotrol的對象更換segmnt_cntrl。試試這個,它可以幫助你實現你的全部目標。

感謝

+3

除了你的第一段,這個答案是正確的。 'forState:'中的'UIControlState'可以用來設置正常和選定段文本的屬性。 – jrturton

+0

謝謝,你是正確的@ jrturton。它完成了錯誤。 –

+0

你應該編輯你的答案,使其正確。 – jrturton

2

沒有標準的API來設置一個UISegmentedControl單個段的文字屬性。您可以採用未經推薦的方法挖掘分段控件的視圖層次結構,找到所需的UILabel(如果有)並設置該標籤的屬性。更好的方法是查找(或寫入)模擬UISegmentedControl的自定義控件,並允許以您需要的方式對單個段進行自定義。

編輯:

其實,我從錯誤的角度看待這個問題。我的回答是基於試圖設置特定分段索引的屬性。但事實上,這可以通過設置UIControlStateSelected狀態的文本屬性來實現。對困惑感到抱歉。

+0

對於特定的控制狀態,您可以使用UIAppearance方法設置文本屬性。所以這個答案是錯誤的。 – jrturton

+0

@jrturton當然。我的錯。我從細分市場的角度考慮這個問題。但在這種情況下,可以爲突出顯示的狀態完成。我會更新我的答案。謝謝 – rmaddy

18

如果您需要更改高亮顯示的段的文本顏色的iOS 7,這裏是一個解決方案(我花了一段時間來尋找,但thanks to this post):

[[UISegmentedControl appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor colorBlack]} forState:UIControlStateSelected]; 
+0

可以請您告訴我如果要將突出顯示的文本顏色以及常規段更改爲黑色,該怎麼做。現在,它的顏色是藍色 –

+0

@NehaDangui,這將是用'UIControlStateNormal'替代'UIControlStateSelected'(或者如果需要的話,則是'UIControlStateHighlighted')。 –

2

由於能夠引用@我 - 答

對於斯威夫特:

UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red], for: .selected) 
0

更新@Babul普拉巴卡爾的答案斯威夫特3,因爲半打微小的事情發生了變化:

UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red as Any], for: .selected) 
0

您可以使用HMSegmentedControl對所有類型的技巧和對待。

使用HMsegmentedController更改字體太簡單了。 在設置HMSegmentedController的函數中添加一個描述屬性的字典並將其傳遞給selectedTitleTextAttributes屬性,示例代碼如下。

-(void)setHMSegmentController { 
    [self.segmentView setSectionTitles:@[@"COURSES", @"ASSESSMENTS"]]; 
    NSDictionary *highlightedAttributes = [NSDictionary dictionaryWithObject:[UIColor blackColor] forKey:NSForegroundColorAttributeName]; 

    self.segmentView.selectedTitleTextAttributes = highlightedAttributes; 
    [self.segmentView addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged]; 
} 

使用此選定的選項卡將使用黑色突出顯示。