Objective- C延迟循环运行时间



我试图在objective-c中编写一个for循环,将显示一堆注释视图,这些注释视图中的每一个将依次创建一个自定义callout视图(只是一个UIView子类)在屏幕中间的图片)。

然而,我希望用户能够抓住callout视图并暂停for循环(延迟循环继续直到用户放开屏幕),当他们放开屏幕时,for循环应该继续并立即转到下一个annotationView。

示例代码:

-(void)displayAnnotation:(MKAnnotationView *)view
{
    // ..blah blah blah
    // ..display some UIView
    // ..delay a second before returning
}
-(void)displayAllAnnotations:(NSMutableArray *)arrayOfAnnotationViews
{
    for (id annotationView in arrayOfAnnotationViews)
    {
        [self displayAnnotation:annotationView]
        // <NEED CODE HERE>
        // <If user holds screen, pause this loop from continuing>
        // <If user lets go, continue loop immediately to next picture>
    }
}

如果您需要更多的信息请告诉我。

你不能使用for循环,因为你在执行for循环时阻塞了主线程。这意味着你的视图将不会接收到触摸事件,直到for循环结束。

我建议使用dispatch_async代替。一个粗略的例子是:

@interface MyClass : NSObject
@property (nonatomic) NSUInteger viewIdx;
@property (nonatomic) NSArray *arrayOfAnnotationViews;
@property (nonatomic) BOOL userIsTappingScreen;
@end
@implementation MyClass
-(void)displayAnnotation:(MKAnnotationView *)view
{
    // ..blah blah blah
    // ..display some UIView
}
-(void)continueIteration
{
    dispatch_async(dispatch_get_main_queue(), ^{
        MKAnnotationView *view = self.arrayOfAnnotationViews[self.viewIdx];
        [self displayAnnotation:view];
        self.viewIdx++;
        if (user is tapping the screen) {
            self.userIsTappingScreen = YES;
        }
        else {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self continueIteration];
            });
        }
    });
 }
 -(void)displayAllAnnotations:(NSMutableArray *)arrayOfAnnotationViews
 {
     self.viewIdx = 0;
     self.arrayOfAnnotationViews = arrayOfAnnotationViews;
 }
 // This method need to be called by your code when the user lifts the finger from the screen
 -(void)userHasSoppedTappingTheScreen
 {
    if (self.userIsTappingScreen) {
        [self continueIteration];
    }
 }
 @end

设置延迟:

double delayInSeconds = 1.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    //code to be executed on the main queue after delay
});

最新更新