如何防止iPhone照片应用程序的自动旋转呢?

时间:2014-03-19 06:56:48

标签: ios uiscrollview uicollectionview uitouch auto-rotation

当屏幕上有手指时,我想阻止UICollectionViewController自动旋转。手指可以移动,设备可以旋转,但只要手指仍然在屏幕上,UICollectionViewController就不应该旋转。

当手指离开屏幕时,UICollectionViewController应立即旋转。正如iPhone照片应用程序那样。

问题:

  1. 如何检测触摸?

    我覆盖了UICollectionView子类中的touchBegan:withEvent:等。但是当UICollectionView开始滚动时,它会调用touchCanceled:withEvent:方法。

    如果我之前开始滚动UICollectionView,touchBegan:withEvent:甚至不会触发。

  2. 如何暂时阻止自动轮换?

    我覆盖视图控制器中的shouldAutorotate以防止旋转。但是当手指离开屏幕时,UICollectionView无法立即旋转。

2 个答案:

答案 0 :(得分:1)

为了检测触摸事件,我建议使用UIGestureRecognizer而不是覆盖UICollectionViewController的触摸事件。这样,您可以在不干扰现有事件处理的情况下通知触摸事件。

您可能需要两个自定义UIGestureRecognizer类来实现此功能,因为我认为UITapGestureRecognizer不会满足您的需求。您可以让一个UIGestureRecognizer通知您手指向下的事件,并在手指抬起时通知您。

为了防止自动旋转,请覆盖shouldAutorotate,就像您已经完成的那样。当您的手势识别器检测到手指已被抬起时,请调用[UIViewController attemptRotationToDeviceOrientation]告诉iOS将UI旋转到当前方向。 (显然确保在调用之前,shouldAutorotate现在将返回YES。)

答案 1 :(得分:1)

请试用此代码:

@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