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 then create a UIView programatically and set's it's x and y coordinates to the CGPoint that I got from the gesture recogniser.
I am able to create it and add it as a subview but the position of the created UIView is different from the location of the TAP.
AnimationView subclasses UIView
My code is below
tappedLocation = gesture.locationInView(self.view) var animationImage: AnimationView = AnimationView() animationImage.frame = CGRectMake(tappedLocation.x, tappedLocation.y, 64, 64) animationImage.contentMode = UIViewContentMode.ScaleAspectFill self.view.addSubview(animationImage) animationImage.addFadeAnimation(removedOnCompletion: true)
Is there anything I am doing wrong?
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
animationImage.frame.size = CGSizeMake(100, 100) animationImage.center = tappedLocation