I need to be able to create and display a UIView at a a certain CGPoint.
So far I have a gesture recogniser that is added as a subview to the main view.
I th
Your problem is, that the you want that the center of the view is the point you clicked. At the moment the top left corner of your UIView
will be the point you touched. So try that:
var frameSize:CGFloat = 64
animationImage.frame = CGRectMake(tappedLocation.x - frameSize/2, tappedLocation.y - frameSize/2, frameSize, frameSize)
As you see, Now you set the width and height before and adjust the x and y so that the center of your view is the point you touched.
But a better way is, like Rob mentioned in his answer to just set the center of the view to your location. That way you only have to set the size of your frame and use the CGSizeMake
instead the CGRectMake
method:
animationImage.frame.size = CGSizeMake(100, 100)
animationImage.center = tappedLocation
Let's create a Tap Gesture and assign it to a View
let tapGesture = UITapGestureRecognizer()
tapGesture.addTarget(self, action: "tappedView:") // action is the call to the function that will be executed every time a Tap gesture gets recognised.
let myView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
myView.addGestureRecognizer(tapGesture)
Every time you tap a view with the assigned Tap Gesture, this function gets called.
func tappedView(sender: UITapGestureRecognizer) {
// Now you ca access all the UITapGestureRecognizer API and play with it however you want.
// You want to center your view to the location of the Tap.
myView.center = sender.view!.center
}
Just set its center
:
animationImage.center = tappedLocation