我让用户移动一个对象,当移动结束时,它将更新显示并播放声音。这一切都很好,但我不想在视图首次加载时播放声音。我如何防止这种情况发生?我需要在viewDidLoad中添加一些东西吗?这是触发事件的代码。谢谢你的帮助。 `
// Updates the text field with the current rotation angle and play sound.
- (void) updateTextDisplay
{
NSError *error = nil;
if (imageAngle >=0 && imageAngle <=180){
ComplimentPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"nice" ofType:@"m4a"]] error:&error];
ComplimentPlayer.delegate = self;
textDisplay.text = [NSString stringWithFormat:@"blah blah blah"];
} else if (imageAngle >180 && imageAngle <=360){
ComplimentPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"good" ofType:@"m4a"]] error:&error];
ComplimentPlayer.delegate = self;
textDisplay.text = [NSString stringWithFormat:@"blah blah"];
}
NSTimeInterval playbackDelay = 0.5;
[ComplimentPlayer playAtTime: ComplimentPlayer.deviceCurrentTime + playbackDelay];
} `
答案 0 :(得分:1)
编辑:整个视图是重新加载还是只是UILabel?
设置一个int值以检查视图首次加载时,将值存储在用户默认值中,并在视图重新加载时更新该值。然后在播放声音时使用if逻辑进行进一步比较。
在viewWillAppear
中 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];//Add this or make it an ivar
int a = 0;
int b = ++a; //set int to add 1 to itself
[defaults setInteger:b forKey:@"viewNumber"];
[[NSUserDefaults standardUserDefaults]synchronize];
- (void) updateTextDisplay
{
NSError *error = nil;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; //Add this or make it an ivar
if (imageAngle >=0 && imageAngle <=180 && [defaults integerForKey@"viewNumber" >=2) //Add this here
{
ComplimentPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:@"nice" ofType:@"m4a"]] error:&error];
ComplimentPlayer.delegate = self;
textDisplay.text = [NSString stringWithFormat:@"blah blah blah"];
} else if (imageAngle >180 && imageAngle <=360 && [defaults integerForKey@"viewNumber">=2) //Add this here
{
ComplimentPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: [[NSBundle mainBundle]
pathForResource:@"good" ofType:@"m4a"]] error:&error];
ComplimentPlayer.delegate = self;
textDisplay.text = [NSString stringWithFormat:@"blah blah"];
}
NSTimeInterval playbackDelay = 0.5;
[ComplimentPlayer playAtTime: ComplimentPlayer.deviceCurrentTime + playbackDelay];
在AppDelegate中添加
- (void)applicationWillTerminate:(UIApplication *)application
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:0 forKey:@"viewNumber"]; //this restores the value to 0 upon termination
[[NSUserDefaults standardUserDefaults]synchronize];
}
答案 1 :(得分:1)
将updateTextDisplay方法分成两个方法
- (void) updateTextDisplay;
- (void) playUpdateTextSound;
首次加载视图时不要调用playUpdateTextSound()。 并在调用updateTextDisplay()
之后调用playUpdateTextSound()