[英]How do I drag a UIImage in swift 4
I currently have the code to move the UIImage to wherever I tap on the screen, however my app requires the user to be able to drag the image about on the screen and my current code doesn't do that.我目前有代码将 UIImage 移动到我在屏幕上点击的任何位置,但是我的应用程序要求用户能够在屏幕上拖动图像,而我当前的代码不会这样做。 I am new to the language so any help would be appreciated.我是该语言的新手,因此将不胜感激。 Here is my current code for getting the location of the touch:这是我当前获取触摸位置的代码:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?{ if let touch = touches.first { let location = touch.location(in: self.view)
You could do it yourself by implementing both touchesBegan()
and touchesMoved()
, but you'd be better off using a UIPanGestureRecognzier
.您可以通过同时实现touchesBegan()
和touchesMoved()
来自己完成,但最好还是使用UIPanGestureRecognzier
。 I'd suggest finding a sample project that lets you drag views using UIPanGestureRecognzier
.我建议找一个示例项目,让您可以使用UIPanGestureRecognzier
拖动视图。 It will save you some head-scratching.它会让你省去一些麻烦。
I had made cube which is basically a UIView that can be dragged around and the info changes inside the cube.我制作了一个立方体,它基本上是一个 UIView,可以四处拖动,立方体内的信息也会发生变化。 I used the following function to drag the cube in the view.我使用以下 function 在视图中拖动立方体。 See if it helps看看有没有帮助
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.