我製作了一個自定義開關,用於開啓和關閉我的遊戲「光學戰鬥」中的聲音效果,但由於某些原因,按下該按鈕時會使開關移動到不同位置,但不起作用在第一次點擊。後來的水龍頭工作,而不是第一個。UIButton無法在第一個水龍頭上工作
在IBAction爲爲按鈕我有:
- (IBAction)theSwitch:(id)sender {
NSUserDefaults *toggle = [NSUserDefaults standardUserDefaults];
if (_toggle == 1) {
[UIView animateWithDuration:0.3 animations:^{
audioToggle.frame = CGRectMake(985.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height);
}];
_toggle ++;
[toggle setInteger:_toggle forKey:@"toggleState"];
[toggle synchronize];
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"audioOn"];
}
else {
[UIView animateWithDuration:0.3 animations:^{
audioToggle.frame = CGRectMake(924.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height);
}];
_toggle --;
[toggle setInteger:_toggle forKey:@"toggleState"];
[toggle synchronize];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"audioOn"];
}
}
而在viewDidLoad中,檢查開關的狀態,並調整它以顯示正確的位置(開或關):
- (void)viewDidLoad
{
[super viewDidLoad];
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"audioOn"]) {
[audioToggle setFrame:CGRectMake(924.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height)];
_toggle = 2;
}
else {
[audioToggle setFrame:CGRectMake(985.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height)];
_toggle = 1;
}
編輯:我用這個來解決我的問題,在IBAction爲爲按鈕:
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"audioOn"]) {
[UIView animateWithDuration:0.3 animations:^{
audioToggle.frame = CGRectMake(985.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height);
}];
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"audioOn"];
}
else {
[UIView animateWithDuration:0.3 animations:^{
audioToggle.frame = CGRectMake(924.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height);
}];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"audioOn"];
}
爲什麼不使用選定的布爾值? – amar
我認爲這是一個邏輯錯誤。試試我的答案.. –
我已經切換到布爾值,我會看看是否修復它。 –