自从我开始使用 xCode 以来,我一直在使用故事板。今天我一直在尝试使用 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