我正在尝试以水平和垂直方式预览图像的幻灯片,我希望能够在用户停止滚动时做一些事情,并在5秒后做这些事情。我使用2个计时器来处理这个,但我需要一些同步,或者我的方法可能不对!为什么我使用2个计时器:因为我想在主视图(-(void)touchesBegan
和-(void)touchesEnded
)中处理滚动并在scrollView(UIScrollView delegate
)上滚动。我的代码在下面,我希望有人可以帮助:)。感谢。
// This is the slideShow view controller
// It display all the images with preview (right, left, up and down)
@interface ImageSlideShowViewController : UIViewController<UIScrollViewDelegate>
{
UIScrollView *scrollViewForSlideShow;
// Timers
NSTimer *autoscrollTimer;
NSTimer *mainViewTimer;
}
@end
@implementation ImageSlideShowViewController
#pragma mark Touch handling
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event{
....
// Invalidate all timers
[autoscrollTimer invalidate];
autoscrollTimer = nil;
[mainViewTimer invalidate];
mainViewTimer = nil;
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
....
assert(mainViewTimer == nil);
mainViewTimer = [NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:@selector(allViewTimerFireMethod:)
userInfo:nil
repeats:NO];
// prev image horizontal
...
// next image horizontal
....
// prev image vertical
...
// next image vertical
....
}
#pragma mark -
#pragma mark UIScrollView delegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
// Invalidate all timers
[autoscrollTimer invalidate];
autoscrollTimer = nil;
[mainViewTimer invalidate];
mainViewTimer = nil;
}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
//Doing some management stuff here
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
if (!scrollView.dragging)
{
//Doing some management stuff here
assert(autoscrollTimer == nil);
autoscrollTimer = [NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:@selector(timerFireMethod:)
userInfo:nil
repeats:NO];
}
}
#pragma mark -
#pragma mark Timers methods
- (void)timerFireMethod:(NSTimer*)theTimer
{
autoscrollTimer = nil;
// Call a method that dispaly the image
}
- (void)allViewTimerFireMethod:(NSTimer *)theTimer
{
mainViewTimer = nil;
// Call a method that dispaly the image (same as the method called above)
}
@end
答案 0 :(得分:0)
我认为你可以摆脱两个定时器并定义一个中间函数,比如enableTimerFor:
,你可以从-scrollViewDidEndDecelerating:
和-touchesEnded:withEvent:
调用,而不是在那里创建2个定时器
enableTimerFor:
基本上会创建计时器并安排它:
-(void)enableTimerFor:(NSUInteger)callerId {
viewTimer = [NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:@selector(timerFired:)
userInfo:nil
repeats:NO];
}
-(void)timerFired {
// do whatever you need to
}
它将被称为:
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
....
[self enableTimerFor:kTouchesEnded];
....
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
if (!scrollView.dragging) {
//Doing some management stuff here
[self enableTimerFor:kScrollEnded];
}
....
}
就像那样,你在同步方面没有问题。另请注意,我认为enableTimerFor:
有一个参数可以让您识别它是从一个函数还是另一个函数调用的,但是如果您不需要区分,您可以轻松地决定将其删除这两个案例。
我不确定这个建议是否适合您,因为我不知道您的解决方案的所有细节,但我认为这是我提供的最直接的建议。