2013-03-15 30 views
0

我有一個選項卡欄控制器和2個視圖控制器連接到它。 在他們每個人都有一個代碼自動滾動一些圖像,併爲每個圖像播放不同的聲音。在標籤欄控制器中的視圖控制器之間切換時停止運行代碼

問題是,當我在兩個視圖控制器之間導航時,聲音和視覺動畫並不停止在我要離開的視圖控制器中。

我該如何停止視控制器中的所有內容?

- (void)scrollingTimer { 
// access the scroll view with the tag 
UIScrollView *scrMain = (UIScrollView*) [self.view viewWithTag:1]; 
// same way, access pagecontroll access 
UIPageControl *pgCtr = (UIPageControl*) [self.view viewWithTag:12]; 
// get the current offset (which page is being displayed) 
CGFloat contentOffset = scrMain.contentOffset.y; 
// calculate next page to display 
int nextPage = (int)(contentOffset/scrMain.frame.size.height) + 1 ; 
// if page is not 10, display it 
if(nextPage!=10) { 
    if (player.isPlaying == YES) 
     [player stop]; 

    NSString *path; 
    NSError *error; 
    path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"cif%02i",nextPage+1] ofType:@"m4a"]; 
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) 
    { 
     player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error]; 
     player.volume = 0.5f; 
     [player prepareToPlay]; 
     [player setNumberOfLoops:0]; 
     [player play]; 
    } 


    [scrMain scrollRectToVisible:CGRectMake(0, nextPage*scrMain.frame.size.height, scrMain.frame.size.width, scrMain.frame.size.height) animated:YES]; 
    pgCtr.currentPage=nextPage; 
    // else start sliding form 1 :) 


} 

回答

4

雖然一個UITabBarController管理它管理的,你沒有得到任何具體的保證,因爲他們在創建和銷燬時,視圖控制器的生命週期 - 我懷疑它從發佈到不同版本。

UITabBarController提供委託接口 - UITabBarControllerDelegate - 並且特別是

- (void)tabBarController:(UITabBarController *)tabBarController 
    didSelectViewController:(UIViewController *)viewController` 

方法 - 用於這個目的。

最簡單的方法是創建一個子類UITabBarController,它也實現了委託。

TabBarController.h

#import <UIKit/UIKit.h> 

@interface TabBarController : UITabBarController<UITabBarControllerDelegate> 

@end 

TabBarController.m

@implementation TabBarController 


- (void)viewDidLoad 
{ 
    // other initialisation here 
    self.delegate = self; 
} 

- (void)tabBarController:(UITabBarController *)tabBarController 
didSelectViewController:(UIViewController *)viewController 
{ 
    if (viewController != myViewController) 
    { 
      // tell it to stop doing things 
    } 
} 
@end 
0

在我的應用我有viewWillDisappear暫停。 爲了讓它在我回到視圖時播放,我在viewWillAppear中檢查暫停。

相關問題