我在我的游戏《光学战斗》中制作了一个自定义开关来打开和关闭音效,但由于某种原因,当点击时将动画开关移动到不同位置的按钮在第一次点击时不起作用。随后的水龙头工作,只是不是第一个。
在按钮的 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"];
}