Swift4:如何在视图中限制平移?

时间:2019-03-26 18:23:07

标签: swift uiview uigesturerecognizer

我需要限制屏幕,以便有有限的空间拖动UIView。 这是我的UIPanGestureRecognizer:

@IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
        let translation = recognizer.translation(in: self.view)
        let statusFrame = UIApplication.shared.statusBarFrame


        if let recognizerView = recognizer.view {
            if recognizerView.frame.origin.x < 0.0 {
                recognizerView.frame.origin = CGPoint(x: 0.0, y: recognizerView.frame.origin.y)
            }
            if recognizerView.frame.origin.y < statusFrame.height {
                recognizerView.frame.origin = CGPoint(x: recognizerView.frame.origin.x, y: statusFrame.height)
            }
            if recognizerView.frame.origin.x + recognizerView.frame.size.width > view.frame.width {
                recognizerView.frame.origin = CGPoint(x: view.frame.width - recognizerView.frame.size.width, y: recognizerView.frame.origin.y)

            }
            if recognizerView.frame.origin.y + recognizerView.frame.size.height > view.frame.height {
                recognizerView.frame.origin = CGPoint(x: recognizerView.frame.origin.x, y: view.frame.height - recognizerView.frame.size.height)
            }
        }

        if let centerX = recognizer.view?.center.x, let centerY = recognizer.view?.center.y {
            recognizer.view?.center = CGPoint.init(x: centerX + translation.x , y: centerY + translation.y)
            recognizer.setTranslation(CGPoint.zero, in: self.view)
        }

        view.bringSubviewToFront(view1)
        recognizer.setTranslation(CGPoint.zero, in: self.view)
}

我找到了在此处限制视图的解决方案,但这设置了怪异的屏幕限制:我只能将UIView拖动到屏幕的一小部分,但无法解决此问题。此外,如果我尝试在其他设备上使用不同的屏幕尺寸都有不同的限制。有没有办法设置通用限制?

所以我的问题是:

  • 修复屏幕限制;
  • 设置通用屏幕限制。

如果您能告诉我甚至在哪里我必须编辑代码以更改限制,也请告诉我。

0 个答案:

没有答案