How can I create a UIView at a certain CGPoint?

前端 未结 3 465
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-17 01:44

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

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-17 02:09

    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
    

提交回复
热议问题