使用平移手势在屏幕的有限区域中移动UIView

时间:2018-02-20 11:43:46

标签: ios swift uipangesturerecognizer

在我的应用程序中,有一个UIView,当用户在给定边界内的超级视图上沿y方向平移时,应该在y方向上移动。

这是应该如何运作的

enter image description here

这是我的代码

@IBOutlet weak var uiview: UIView!
// self.view is the supper view of uiview

var uiviewLastCenterPosition = CGPoint(x: 0, y: 0)
var lastTranslation = CGPoint(x: 0, y: 0)

override func viewDidAppear(_ animated: Bool) {
    self.uiviewLastCenterPosition = self.uiview.center
}

@IBAction func supperViewPan(_ sender: UIPanGestureRecognizer) {

    switch sender.state {

    case .began:
        break
    case .changed:

        let uiviewTop = self.uiview.frame.origin.y
        let uiviewBottom = self.uiview.frame.origin.y + self.uiview.frame.size.height

        let velocity = sender.velocity(in: self.view)

        if velocity.y > 0.0 { // down

            if uiviewBottom < 600{

                self.uiview.center.y = (self.uiviewLastCenterPosition.y) + sender.translation(in: self.view).y
                self.lastTranslation = sender.translation(in: self.view)
            }else{
                sender.setTranslation(self.lastTranslation, in: self.view)
            }

        }else if velocity.y < 0.0 { // up

            if uiviewTop > 100{

                self.uiview.center.y = (self.uiviewLastCenterPosition.y) + sender.translation(in: self.view).y
                self.lastTranslation = sender.translation(in: self.view)
            }else{
                sender.setTranslation(self.lastTranslation, in: self.view)
            }
        }
        break

    case .ended:

        self.uiviewLastCenterPosition = self.uiview.center
        break

    default:
        break
    }
}

当用户缓慢移动时,所有工作都很完美。但是当用户快速播放时,uiview超越了界限。

enter image description here enter image description here

有人可以帮我解决这个问题。我想将视图完全移到这些边界内。任何帮助将受到高度赞赏。

0 个答案:

没有答案