繁体   English   中英

我如何在swift中拖动一个UIImage 4

[英]How do I drag a UIImage in swift 4

我目前有代码将 UIImage 移动到我在屏幕上点击的任何位置,但是我的应用程序要求用户能够在屏幕上拖动图像,而我当前的代码不会这样做。 我是该语言的新手,因此将不胜感激。 这是我当前获取触摸位置的代码:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?{ if let touch = touches.first { let location = touch.location(in: self.view)

您可以通过同时实现touchesBegan()touchesMoved()来自己完成,但最好还是使用UIPanGestureRecognzier 我建议找一个示例项目,让您可以使用UIPanGestureRecognzier拖动视图。 它会让你省去一些麻烦。

我制作了一个立方体,它基本上是一个 UIView,可以四处拖动,立方体内的信息也会发生变化。 我使用以下 function 在视图中拖动立方体。 看看有没有帮助

   var draggableCube = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))

@objc func panGestureDetected(panGestureRecognizer: UIPanGestureRecognizer) {
        
    let translation = panGestureRecognizer.translation(in: self.view)
    var changeX : CGFloat = 0
    var changeY : CGFloat = 0
    
    if translation.x + self.draggableCube.frame.maxX > self.view.bounds.maxX {
        // prevents it to go outside of the bounds from right side
        changeX = self.view.bounds.maxX - self.draggableCube.frame.maxX
    } else if translation.x + self.draggableCube.frame.minX < self.view.bounds.minX{
        // prevents it to go outside of the bounds from right side
        changeX = self.view.bounds.minX - self.draggableCube.frame.minX
    } else {
        // translation is within limits
        changeX = translation.x
    }
    if translation.y + self.draggableCube.frame.maxY > self.view.bounds.maxY {
        // prevents it to go outside of the bounds from bottom
        changeY = self.view.bounds.maxY - self.draggableCube.frame.maxY
    } else if translation.y + self.draggableCube.frame.minY < self.view.bounds.minY {
        // prevents it to go outside of the bounds from top
        changeY = self.view.bounds.minY - self.draggableCube.frame.minY
    } else {
        // translation is within limits
        changeY = translation.y
    }

    self.draggableCube.center = CGPoint(x: self.draggableCube.center.x + changeX, y: self.draggableCube.center.y + changeY)

    panGestureRecognizer.setTranslation(CGPoint.zero, in: self.view)

    if panGestureRecognizer.state == .ended {
        // implement action what you want to do after the gragging ended
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM