2015-06-19 76 views
0

我想隨機更改背景顏色作爲超時效果屏幕上的任意按鈕都被點擊。 我想用開/關UIButton來控制這種效果。 點擊ChangeColorButton只記錄「關」從不「開」。不知道該怎麼辦?感謝大家!!iOS:使用多個按鈕更改背景顏色

編輯的代碼到目前爲止! 在.H

@property(nonatomic,readwrite) BOOL shouldChangeColor; 

in .m 
- (IBAction)ChangeColorButton:(UIButton*)sender { 

    // self.shouldChangeColor = !sender.selected; 
    sender.selected = !sender.selected; 
    if(sender.selected) 
    { 
     NSLog(@"Switch is ON"); 
     //Make it off now 
     // sender.selected=NO; 
    // self.shouldChangeColor=TRUE; 



    } 
    else 

     NSLog(@"Switch is OFF"); 
    //Make it on now 
    // sender.selected=YES; 
    self.shouldChangeColor=TRUE; 

     } 

- (void)randomColor{ 
    int r = arc4random() % 255; 
    int g = arc4random() % 255; 
    int b = arc4random() % 255; 

    UIColor *color = [UIColor colorWithRed:(r/255.0) green:(g/255.0) blue:(b/255.0) alpha:1.0]; 

    [self.view setBackgroundColor:color]; 

} 

回答

1

因爲你不是從任何地方改變按鈕

- (IBAction)ChangeColorButton:(UIButton*)sender { 
    //self.shouldChangeColor = sender.selected; 
    sender.selected = !sender.selected; //If you do this 
    if(sender.selected) 
    { 
     self.shouldChangeColor=YES; 
     NSLog(@"Switch is ON"); 
     //Make it off now 
     //sender.selected=NO; You Don't have to do this 
     [self randomColor];//If you want to change the color when switch is on 

    } 
    else{ 
     self.shouldChangeColor=NO; 
     NSLog(@"Switch is OFF"); 
     //Make it on now 
     //sender.selected=YES; You Don't have to do this 
     [self.view setBackgroundColor:[UIColor blackcolor]];//Check the syntax 
    } 
} 

的選擇現在調用此函數來改變顏色​​

- (void)randomColor{ 
if(self.shouldChangeColor){ 


int r = arc4random() % 255; 
int g = arc4random() % 255; 
int b = arc4random() % 255; 

UIColor *color = [UIColor colorWithRed:(r/255.0) green:(g/255.0) blue:(b/255.0) alpha:1.0]; 

[self.view setBackgroundColor:color]; 
} 
} 
+0

感謝souvickcse!當添加這些線是有效的。我還加了一個! to!sender.selected。現在問題是ChangeColorButton不會「關閉」 –

+0

你可以更新你的最新代碼嗎? – souvickcse

+0

我將在原始端口上發佈代碼,謝謝!更新了上面的代碼。完全黑客攻擊周圍的東西。非常感謝您的幫助! –