2014-09-02 75 views
6

我想更改關閉狀態下UISwitch中onTintColor的顏色。該開關在桌面視圖中並且以編程方式進行切換。如何將UISwitch默認顏色更改爲關閉狀態?

[settingsSwitch setBackgroundColor:[UIColor whiteColor]]; 
    [settingsSwitch setTintColor:[UIColor whiteColor]]; 
    [settingsSwitch setThumbTintColor:[UIColor redColor]]; 
    [settingsSwitch setOnTintColor:[UIColor colorWithRed:138/256.0 green:9/256.0 blue:18/256.0 alpha:1]]; 

enter image description here

這是結果我得到當我設置背景顏色爲白色。

enter image description here

而且沒有背景,我得到紅色是我的單元格的顏色。

enter image description here

,這就是我想要的結果,當開關在onTintColor應該b暗紅色,並且在關閉狀態時,它應該是白色。

我試圖與這行代碼

[settingsSwitch setOnImage:[UIImage imageNamed:@"on.png"]]; 
[settingsSwitch setOffImage:[UIImage imageNamed:@"off.png"]]; 

但其不改變圖像上設定開關的圖像。 我想改變開關處於關閉狀態的顏色。 希望我已經清楚地解釋了我的問題。感謝您提前幫忙。

+0

不知道這是一個好主意。它看起來像開關關閉。關閉開關看起來像是開着。 (因爲它有一個明亮的,白色的,積極的顏色)。 – Marc 2014-09-02 06:29:41

+2

我同意,但這是客戶的要求。 – 2014-09-02 06:43:17

+0

@iOSDeveloper,客戶永遠是對的:) – 2014-09-02 07:42:33

回答

7

您可以使用以下代碼來滿足要求。

你的viewDidLoad

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    // Do any additional setup after loading the view, typically from a nib. 

    [self.view setBackgroundColor:[UIColor redColor]]; 

    settingsSwitch.layer.cornerRadius = 16.0; // you must import QuartzCore to do this 


    if (settingsSwitch.on) { 
     NSLog(@"If body "); 
     [settingsSwitch setThumbTintColor:[UIColor redColor]]; 

     [settingsSwitch setBackgroundColor:[UIColor whiteColor]]; 
     [settingsSwitch setOnTintColor:[UIColor whiteColor]]; 

    }else{ 
     NSLog(@"Else body "); 

     [settingsSwitch setTintColor:[UIColor clearColor]]; 

     [settingsSwitch setThumbTintColor:[UIColor redColor]]; 

     [settingsSwitch setBackgroundColor:[UIColor colorWithRed:138/256.0 green:9/256.0 blue:18/256.0 alpha:1]]; 
    } 
} 

方法,其中狀態改變IBAction爲被調用。

- (IBAction)switchStatusChange:(UISwitch *)sender 
{ 
    if (sender.on) { 
     NSLog(@"If body "); 
     [sender setThumbTintColor:[UIColor redColor]]; 

     [sender setBackgroundColor:[UIColor whiteColor]]; 
     [sender setOnTintColor:[UIColor whiteColor]]; 

    }else{ 
     NSLog(@"Else body "); 

     [sender setTintColor:[UIColor clearColor]]; 

     [sender setThumbTintColor:[UIColor redColor]]; 

     [sender setBackgroundColor:[UIColor colorWithRed:138/256.0 green:9/256.0 blue:18/256.0 alpha:1]]; 
    } 
} 
+0

這實際上是可行的,但它與拇指動畫(向左或向右)一起旋轉。任何解決方法? – Legoless 2014-10-02 07:14:23

+0

我們怎麼能使它平滑 – 2015-07-16 15:59:17

3

你可以用你第一種方法+添加邊框半徑,以除去不需要的角落:

slider.backgroundColor = [UIColor whiteColor]; 
slider.layer.cornerRadius = 18.0; 

最初從this答案。

+0

cornerRadius影響邊界角落,它的一個不好的解決方案 – 2016-08-24 21:53:37