2010-08-09 27 views
1

嗨,在搖動手勢時務必滾動UIScrollView

我有一個視圖,在屏幕上有三個UIScrollViews。我想隨機滾動UIScrollViews到不同的位置,每當用戶搖動iPhone,但我無法完成。

我在我的ViewController類中實現了以下功能來檢測和處理搖動手勢,3個UIScrollViews也屬於同一個類。檢測到搖動手勢,但UIScrollViews不會更改。我究竟做錯了什麼??

我已經試過motionBegan和motionEnded。

-(BOOL)canBecomeFirstResponder { 
    return YES; 
} 

-(void)viewDidAppear:(BOOL)animated { 
    [super viewDidAppear:animated]; 
    [self becomeFirstResponder]; 
} 

- (void)viewWillDisappear:(BOOL)animated { 
    [self resignFirstResponder]; 
    [super viewWillDisappear:animated]; 
} 

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event 
{ 
    if (motion == UIEventSubtypeMotionShake) 
    { 
    int randomTag = arc4random() % [dirContents count]; 

    CGRect nextImageView = [[scrollView1 viewWithTag:2] frame]; 
    [scrollView1 scrollRectToVisible:nextImageView animated:YES]; 

    randomTag = arc4random() % [dirContents count]; 
    nextImageView = [[scrollView2 viewWithTag:4] frame]; 
    [scrollView2 scrollRectToVisible:nextImageView animated:YES]; 

    randomTag = arc4random() % [dirContents count]; 
    nextImageView = [[scrollView3 viewWithTag:4] frame]; 
    [scrollView3 scrollRectToVisible:nextImageView animated:YES]; 
    NSLog(@"Shake Detected End"); 
    } 
} 

謝謝

回答

0

做你是否嘗試過使用SetContentOffset代替scrollRectToVisible但UITableView的?

如果您的tableView中的圖像高度相同,則每個「元素」的偏移量始終相同。

[scrollView3 setContentOffset:yourRandomOffsetInPixels animated:YES]; 

也許這有效。 也認爲,這問題可能是您的抖動檢測法在一個單獨的線程運行,這將意味着你必須打電話給你的motionEnded方法上mainthread像這樣:

[self performSelectorOnMainThread:@selector(motionEnded) withObject:nil waitUntilDone:NO]; 
+0

我還沒有嘗試過使用SetContentOffset,因爲我曾經使用過scrollRectToVisible。也許我可以試試看。 我該在哪裏準確地使用這條線?我不明白。 [self performSelectorOnMainThread:@selector(motionEnded)withObject:nil waitUntilDone:NO]; – 2010-08-09 15:25:31

+0

scrollRectToVisible是一個棘手的韌皮。如果它認爲定義的矩形是可見的,它將忽略該請求,並且我發現它在很多場合都沒有做到我想要的。 setContentOffset通常修復它。 – mtrc 2010-08-09 15:30:50

+0

是的,它與SetContentOffset一起工作。謝謝samsam和mtc06! 雖然我會喜歡它與scrollRectVisible一起工作。 – 2010-08-09 15:44:27

0

你檢查你的nextImageView變量,看它是否是正確的?

進一步,如果你想將有一個老虎機的運動,我會建議你使用,而不是由自己與滾動視圖

+0

是的,我試圖讓它像一個老虎機,它可以隨機搖一搖,也可以通過拖動來改變單個插槽。 這是可以與表視圖?如果我想要在表格視圖中加載圖像怎麼辦? – 2010-08-09 15:22:47

+0

你可以在你的TableView中加載任何東西。在每個TableViewCell中,您可以將任何視圖添加到contentView ...但是,將TableView滾動到特定的行號會更容易,它會自行計算它的位置。 – TheSquad 2010-08-09 18:26:37

0

只是一個簡單的問題。在你的示例代碼,您生成一個隨機標籤:

randomTag = arc4random() % [dirContents count]; 

但你(在這種情況下4)使用特定的標記值?我認爲在使用randomTag值時它仍然不起作用?而你只是在做一些測試?

nextImageView = [[scrollView2 viewWithTag:4] frame]; 
+0

是的,那只是一些測試,看看隨機變量是否有問題。 – 2010-08-09 15:23:16