2014-12-11 29 views
0

這是我要的效果:在UISegmentedControl中,如何將正常顏色與所選顏色分開設置?

enter image description here

這是我到目前爲止有:

enter image description here

可可不允許同時設置圖標和每段的文字,所以我被迫將文字刻錄成圖像:

self.segmentedControl = [[UISegmentedControl alloc] initWithItems:@[ 
    [UIImage imageNamed:@"segmentedControlContacts"], 
    [UIImage imageNamed:@"segmentedControlOtherApps"] 
]]; 

我必須完成的最後一件事是將正常(未選中)的片段變成灰色,而不是其選定的/淡色的藍色。以下沒有工作:

// themeColor is defined as a shade of blue in a category 
[UIView appearance].tintColor = [UIColor themeColor]; 
[[UISegmentedControl appearance] 
    setBackgroundImage:[UIImage imageNamed:@"segmentedControlEdgeNormal"] 
    forState:UIControlStateNormal barMetrics:UIBarMetricsDefault]; 
[[UISegmentedControl appearance] 
    setBackgroundImage:[UIImage imageNamed:@"segmentedControlEdgeSelected"] 
    forState:UIControlStateSelected barMetrics:UIBarMetricsDefault]; 
[[UISegmentedControl appearance] 
    setTitleTextAttributes:@{ 
     NSForegroundColorAttributeName: [UIColor grayColor] 
    } 
    forState:UIControlStateNormal 
]; 

回答

1

[[UISegmentedControl appearance] setTitleTextAttributes:@{ 
     NSForegroundColorAttributeName: [UIColor grayColor] 
    } 
    forState:UIControlStateNormal 
]; 

將僅適用於分段控制的稱號。如果您從細分受衆羣中移除圖片併爲兩個細分受衆羣添加標題,則此操作肯定會有效。

這不會影響段控制的圖像。

對於映像定製你必須使用方法:

- (void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics 

而且它不會顯示着色顏色如你預期。

建議:

如果你還是堅持要作出這樣的自定義行爲,我建議休假分段控制,而不是創建兩個按鈕,把它們並排覺得自己像一個段控制。

而對於這種行爲,您需要按鈕背景的灰色圖像並更改備用按鈕事件。