平移手势可以用于移动 UIWindows 吗?

Can a pan gesture be used for moving UIWindows?

是否可以通过平移手势识别器移动 UIWindow?我在理解手势的工作原理时遇到了问题,并设法让它在视图中工作,但不是 windows。

是的,你可以。

UIWindowUIView的子类,可以正常添加PanGesture。要移动 window,更改 UIApplication.sharedApplication.delegate.window 的框架,它会正常工作。

创建一个新项目并用下面的代码替换 AppDelegate.m 文件。您可以移动 window.

#import "AppDelegate.h"

@interface AppDelegate ()

@property (nonatomic, strong) UIPanGestureRecognizer* panGesture;
@property (nonatomic, assign) CGPoint lastPoint;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  // Override point for customization after application launch.

  self.panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
  [self.window addGestureRecognizer:_panGesture];
  _needUpdate = YES;

  return YES;
}

- (void)handlePanGesture:(UIPanGestureRecognizer *)panGesture {
  CGPoint point = [panGesture locationInView:self.window];
  CGPoint center = self.window.center;

  if (CGPointEqualToPoint(_lastPoint, CGPointZero)) {
    _lastPoint = point;
  }

  center.x += point.x - _lastPoint.x;
  center.y += point.y - _lastPoint.y;
  self.window.frame = [UIScreen mainScreen].bounds;
  self.window.center = center;

  if (panGesture.state == UIGestureRecognizerStateEnded) {
    _lastPoint = CGPointZero;
  }
}


@end