问题
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?
回答1:
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
回答2:
Just set its center
:
animationImage.center = tappedLocation
回答3:
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
}
来源:https://stackoverflow.com/questions/28660141/how-can-i-create-a-uiview-at-a-certain-cgpoint