I want to prevent a UICollectionViewController from auto rotation when there's a finger on the screen. The finger could move, the device could rotate, but the UICollectionViewController shouldn't rotate whenever the finger is still on screen.
And the UICollectionViewController should rotate immediately when the finger left the screen. As the iPhone photo app does.
Question:
How to detect touch?
I overwrite the touchBegan:withEvent:
etc. in UICollectionView subclass. But when the UICollectionView start scrolling, it calls touchCanceled:withEvent:
method.
If I start scrolling the UICollectionView earlier, the touchBegan:withEvent:
does even not fired.
How to prevent auto rotation temporarily?
I overwrite the shouldAutorotate
in my view controller to prevent rotation. But when the finger left the screen, the UICollectionView can't rotate immediately.
Try this code, please:
@interface BlockAutorotateViewController ()
@property (nonatomic, strong) UILongPressGestureRecognizer *longPressGestureRecognizer;
@property (nonatomic, strong) UISwipeGestureRecognizer *swipeGestureRecognizer;
@property (nonatomic, assign, getter = isPressed) BOOL pressed;
@end
@implementation BlockAutorotateViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.pressed = NO;
self.longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(myLongPressAction:)];
self.longPressGestureRecognizer.minimumPressDuration = 0;
[self.view addGestureRecognizer:self.longPressGestureRecognizer];
self.swipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(mySwipeAction:)];
[self.view addGestureRecognizer:self.swipeGestureRecognizer];
}
- (void)myLongPressAction:(id)sender
{
if ((self.longPressGestureRecognizer.state == UIGestureRecognizerStateEnded) || (self.longPressGestureRecognizer.state == UIGestureRecognizerStateChanged)) {
self.pressed = YES;
}
else if (self.longPressGestureRecognizer.state == UIGestureRecognizerStateBegan) {
self.pressed = NO;
[UIViewController attemptRotationToDeviceOrientation];
}
else {
self.pressed = NO;
}
}
- (void)mySwipeAction:(id)sender
{
if ((self.swipeGestureRecognizer.state == UIGestureRecognizerStateBegan) || (self.longPressGestureRecognizer.state == UIGestureRecognizerStateChanged)) {
self.pressed = YES;
}
else if (self.longPressGestureRecognizer.state == UIGestureRecognizerStateEnded) {
self.pressed = NO;
[UIViewController attemptRotationToDeviceOrientation];
}
else {
self.pressed = NO;
}
}
- (BOOL)shouldAutorotate
{
return (self.isPressed ? NO : YES);
}
@end