我有一个标签栏 Controller 和 2 个 View Controller 连接到它。
在它们中的每一个上都有一个代码可以自动滚动浏览一些图像并为每个图像播放不同的声音。
问题是当我在 2 个 View Controller 之间导航时,声音和视觉动画不会在我要离开的 View Controller 中停止。
如何停止我要离开的 View Controller 中的所有内容?
- (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 :)
}
最佳答案
虽然 UITabBarController
管理它管理的 View Controller 的生命周期,您无法获得关于何时创建和销毁它们的任何具体保证 - 我怀疑它因版本而异。UITabBarController
提供委托(delegate)接口(interface) - UITabBarControllerDelegate
- 特别是
- (void)tabBarController:(UITabBarController *)tabBarController
didSelectViewController:(UIViewController *)viewController`
方法 - 为此目的。
最简单的方法是创建
UITabBarController
的子类这也实现了委托(delegate)。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
关于xcode - 在标签栏 Controller 中的 View Controller 之间切换时停止运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15434964/