Swift:如何设置平移手势的最大/最小?

时间:2019-03-19 21:35:43

标签: swift uiview uigesturerecognizer

注意:我已经尝试过找到的其他答案,但对我没有任何帮助。

我需要为UIView设置屏幕限制,我可以在主视图周围拖动(以便不能将其拖动到视图外部)。另外,我想知道如何使此屏幕限制适应不同的设备。

@IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
let translation = recognizer.translation(in: self.view)
if let view = recognizer.view {
    view.center = CGPoint(x:view.center.x + translation.x,
                              y:view.center.y + translation.y)
}
recognizer.setTranslation(CGPoint.zero, in: self.view)
}

1 个答案:

答案 0 :(得分:0)

以下内容显示了如何在视图控制器(UILabel)的主视图上平移UIViewController控件以及如何将其平移移动限制在后者的可见边界内。请注意,状态栏被假定为可见。因此,顶部边界取决于状态栏的高度。

import UIKit

class ViewController: UIViewController {
    // MARK: - Variables

    // MARK: - IBOutlet
    @IBOutlet weak var label: UILabel!

    // MARK: - IBAction

    // MARK: - Life cycle
    override func viewDidLoad() {
        super.viewDidLoad()

        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
        label.isUserInteractionEnabled = true
        label.addGestureRecognizer(panGesture)
    }

    @objc func handlePan(_ sender: UIPanGestureRecognizer) {
        let translation = sender.translation(in: self.view)
        let statusFrame = UIApplication.shared.statusBarFrame

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

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