2013-05-31 3 views
0

У меня есть представление, которое содержит scrollview и uiwebview с html внутри него. Я пытаюсь, чтобы scrollview медленно автоматически прокручивался вниз, останавливался при касании, а затем перезапускал анимацию в текущей позиции.Имейте UIScrollView Animation Пауза и перезагрузка на жесте Touch

На данный момент у меня есть html-показ, прокрутка прокрутки и касание, останавливающее прокрутку, но я не могу заставить анимацию прокрутки снова запускаться в текущей позиции через определенное количество времени после касания , Вот код:

 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     // Custom initialization 
    } 
    return self; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    NSString *myHTML = @"<html><body><h1>Hello, world!</h1><h1>Hello, world!</h1><h1>Hello, world!</h1><h1>Hello, world!</h1><h1>Hello, world!</h1><h1>Hello, world!</h1><h1>Hello, world!</h1><h1>Hello, world!</h1><h1>Hello, world!</h1><h1>Hello, world!</h1><h1>Hello, world!</h1><h1>Hello, world!</h1><h1>Hello, world!</h1><h1>Hello, world!</h1></body></html>"; 

    [self.webView loadHTMLString:myHTML baseURL:nil]; 

    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(userDidTapWebView)]; 
    [self.webView addGestureRecognizer:recognizer]; 
    recognizer.delegate = self; 
    [recognizer release]; 

    //Start the scrolling 
    [self startAnimation]; 

} 

#pragma mark - Gesture Delegate 

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer 
     shouldReceiveTouch:(UITouch *)touch { 
    //Stop the scrollview from scrolling when the screen is touched 
    [self.scrollView.layer removeAllAnimations]; 

    return YES; 
} 

#pragma mark - Animate Methods 

-(void)startAnimation{ 
    [UIScrollView beginAnimations:@"scrollAnimation" context:nil]; 
    [UIScrollView setAnimationDuration:8.0f]; 
    [self.scrollView setContentOffset:CGPointMake(0 , 100)]; 
    [UIScrollView commitAnimations]; 
} 

-(void)dealloc{ 
    [super dealloc]; 
    [self.webView release]; 
    [self.scrollView release]; 
} 


- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
    // e.g. self.myOutlet = nil; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    return (interfaceOrientation == UIInterfaceOrientationPortrait); 
} 

ответ

0

Вы пропускаете код для запуска анимации снова: how to call a method of multiple arguments with delay

, а также при вызове removeAllAnimations, вид прокрутки будет переходить к конечному положению оно предназначено, так это не действительно приостановлено, как то, что вы хотите.

Вы можете посмотреть на то, как сделать паузу и возобновить анимацию здесь: Is there a way to pause a CABasicAnimation?

Таким образом, помещая их вместе (с дополнительной проверкой еще раз для возобновления анимации, если вид прокрутки прикосновении еще раз):

-(void)pauseLayer:(CALayer*)layer 
{ 
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil]; 
    layer.speed = 0.0; 
    layer.timeOffset = pausedTime; 
} 

-(void)resumeLayer:(CALayer*)layer 
{ 
    CFTimeInterval pausedTime = [layer timeOffset]; 
    layer.speed = 1.0; 
    layer.timeOffset = 0.0; 
    layer.beginTime = 0.0; 
    CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime; 
    layer.beginTime = timeSincePause; 
} 

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer 
     shouldReceiveTouch:(UITouch *)touch { 
    if (self.scrollView.layer.timeOffset>0) { 
     [self resumeLayer:self.scrollView.layer]; //resume the animation on the subsequent touch 
    } 
    else { 
     //first we pause the animation 
     [self pauseLayer:self.scrollView.layer]; 

     //after certain seconds we will start again the animation 
     double delayInSeconds = 2.0; //adjust this value 
     dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); 
     dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ 
      [self resumeLayer:self.scrollView.layer]; 
     }); 
    } 
    return YES; 
} 
+0

Я реализовал код, и методы делегата все еще не подхватили. – user1079052

+0

Какие методы делегата? –

Смежные вопросы