If you want to touch and drag an object around the screen you can do this by setting the object's center property to the location of your touch.
In this example I have an image (UIImageView) that I want to touch and drag.
In this example I have an image (UIImageView) that I want to touch and drag.
Create New Class
import UIKit class DraggableImage: UIImageView { override func touchesMoved(touches: SetI override touchesMoved and am getting the position of my touch and making the center of my image the same position as my touch., withEvent event: UIEvent?) { if let touch = touches.first { let position = touch.locationInView(superview) center = CGPointMake(position.x, position.y) } } }
Setup Image in Xcode
In this example I am using a UIImageView. I dropped an image on my storyboard and I have to make 2 changes.- Set the Custom Class
Set the class to the class that overrides touchesMoved: - Set Interaction
Make sure "User Interaction Enabled" is checked. This allows your touchesMoved override to receive touch event messages. I also unchecked "Multiple Touch" because I'm only using one finger to move my object.
I've just discovered your Swift guide and really like your style, easy to read and understand!
ReplyDeleteI had a problem with Touch & Drag, which doesn't work with Swift 4. After some research, I found the correct syntax as follows for anyone else who needs it:
(edit: the blogspot comment strips out some characters in the code snippet, so the complete code is not shown. The changes are replace uitouch with UITouch, CGPointMake with CGPoint and position.x, position.y with x: position.x, y: position.y)
Hope that makes sense!
class DraggableImage: UIImageView {
override func touchesMoved(_ touches: Set, with event: UIEvent?) {
if let touch = touches.first {
let position = touch.location(in: superview)
center = CGPoint(x: position.x, y: position.y)
}
}
}