如何防止像iPhone照片应用程序自动旋转?
我想阻止UICollectionViewController在屏幕上出现手指时自动旋转。手指可以移动,设备可以旋转,但是当手指仍然在屏幕上时,UICollectionViewController不应该旋转。如何防止像iPhone照片应用程序自动旋转?
当手指离开屏幕时,UICollectionViewController应该立即旋转。正如iPhone照片应用程序一样。
问:
-
如何来检测触摸?
我覆盖了UICollectionView子类中的
touchBegan:withEvent:
等。但是当UICollectionView开始滚动时,它会调用touchCanceled:withEvent:
方法。如果我之前开始滚动UICollectionView,则
touchBegan:withEvent:
甚至不会被触发。 -
如何防止自动旋转暂时?
我在我的视图控制器中覆盖
shouldAutorotate
以防止旋转。但是当手指离开屏幕时,UICollectionView不能立即旋转。
试试这个代码,请:
@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
不一定是'UILongPressGestureRecognizer' – smilingpoplar
@smilingpoplar,你可以使用哪一个来获得这个所需的功能?你测试过上面的例子吗? – mbpro
我试过了你的代码。如果我先移动手指,然后旋转设备,则不起作用。在这种情况下,视图不应该旋转。 – smilingpoplar
为了检测触摸事件,我建议使用UIGestureRecognizer而不是重写UICollectionViewController的触摸事件。这样可以在不干扰现有事件处理的情况下通知触摸事件。
您可能需要两个自定义UIGestureRecognizer类才能实现此目的,因为我不认为UITapGestureRecognizer将满足您的需求。您可以让一个UIGestureRecognizer通知您手指放下事件,另一个手指抬起时通知您。
为防止自动旋转,请重写shouldAutorotate,因为您已完成此操作。当您的手势识别器检测到手指已被抬起时,调用[UIViewController attemptRotationToDeviceOrientation]告诉iOS将UI旋转到当前方向。 (显然,确保shouldAutorotate现在调用之前返回YES。)
你的想法可能有效。但它需要实现两个自定义UIGestureRecognizer。我会尝试一段时间。 – smilingpoplar
杜您的意思是修复设备Orrientation –
我想禁用旋转暂时当有手指触摸。 – smilingpoplar