2012-04-07 56 views
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 

回答

1

第二控制器並沒有真正使用從第一,但是,如果你叫startAccelerometerUpdates而你顯示你的第一個視圖,你可能想阻止他們,你即將呈現第二碼一個如果它不需要它們。

+0

我將源代碼添加到上面的原始問題。你能看到我做錯了什麼使它在下一個視圖控制器上使用這個加速計嗎? – sdlabs 2012-04-07 01:01:51

+0

除了根據文檔,你應該調用'[super viewWillAppear:animated]'和'[super viewWillDisappear:animated]',沒有什麼東西會跳出來。我不認爲**會導致這個問題(但我不確定)。我試圖在startAccel和stopAccel中寫出NSLog()消息,以確保它們在我認爲是時被調用。 – 2012-04-07 01:14:23