Question

HI,

I have a view that has three UIScrollViews on the screen. I want to randomly scroll the UIScrollViews to different positions whenever a user shakes the iPhone, but I am unable to get it done.

I have implemented the following in my ViewController class to detect and handle the shake gesture, the 3 UIScrollViews also belong to the same class. The shake gesture is detected, but the UIScrollViews do not change. What am I doing Wrong??

i have tried both motionBegan and 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");
    }
}

Thank You

Was it helpful?

Solution

Have you tried using SetContentOffset instead of scrollRectToVisible yet?

if the images in your tableView are of equal height the offset per "Element" is always the same.

[scrollView3 setContentOffset:yourRandomOffsetInPixels animated:YES];

maybe this works. also consider, that The Problem might be that your shake-detection Method runs on a separate Thread this would mean that you have to call your motionEnded Method on the mainthread like so:

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

OTHER TIPS

Did you check your nextImageView variable to see if it was correct ?

Further more if you are trying will have the motion of a slot machine, I would recommend you to use UITableView instead of doing it by yourself with scrollView

Just one quick question. In your example code, you generate a random tag:

randomTag = arc4random() % [dirContents count];

but then you use a specific tag value (4 in this case)? I assume it still doesn't work when you use the randomTag value? and that you were just doing some testing?

 nextImageView = [[scrollView2 viewWithTag:4] frame];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top