0
自從我開始使用xCode以來,我一直在使用故事板。今天,我一直在用xib文件嘗試舊的方式。切換xib視圖而不帶前一屏幕的命令
我的第一個視圖有一個加速度計代碼,當我在第二個視圖上時它仍然處於活動狀態。
有沒有辦法來停止第二個視圖控制器從第一個視圖使用代碼?
我正在將第二個視圖頭文件導入到第一個視圖實現文件中,是否正確?如果我刪除該導入,我會得到錯誤。
//
// ViewController.m
#import "ViewController.h"
#import "ViewController2.h"
@interface ViewController()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
-(void)viewWillAppear:(BOOL)animated{
[self startAccel];
//[self view];
}
-(void)viewWillDisappear:(BOOL)animated{
[self stopAccel];
//[self view];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return ((interfaceOrientation == UIInterfaceOrientationPortrait) || (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown));
}
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration{
double const kThreshold = 1.7;
// double const kThreshold = 2.0;
if (fabsf(acceleration.x) > kThreshold
|| fabsf(acceleration.y) > kThreshold
|| fabsf(acceleration.z) > kThreshold){
int randomNumber = arc4random() % 3 + 1;
NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:[NSString stringWithFormat:@"Sound%02d", randomNumber] ofType:@"wav"]];
AVAudioPlayer * soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];
[soundPlayer prepareToPlay];
[soundPlayer play];
}
}
-(void)startAccel{
UIAccelerometer * accel = [UIAccelerometer sharedAccelerometer];
accel.delegate = self;
accel.updateInterval = .25;
}
-(void)stopAccel{
UIAccelerometer * accel = [UIAccelerometer sharedAccelerometer];
accel.delegate = nil;
}
-(IBAction)View2:(id)sender;{
ViewController2 *V2 = [[ViewController2 alloc]
initWithNibName:@"ViewController2"
bundle:nil];
[self.view addSubview:V2.view];
}
@end
我將源代碼添加到上面的原始問題。你能看到我做錯了什麼使它在下一個視圖控制器上使用這個加速計嗎? – sdlabs 2012-04-07 01:01:51
除了根據文檔,你應該調用'[super viewWillAppear:animated]'和'[super viewWillDisappear:animated]',沒有什麼東西會跳出來。我不認爲**會導致這個問題(但我不確定)。我試圖在startAccel和stopAccel中寫出NSLog()消息,以確保它們在我認爲是時被調用。 – 2012-04-07 01:14:23