如何在某个CGPoint上创建UIView? [英] How can I create a UIView at a certain CGPoint?

查看:120
本文介绍了如何在某个CGPoint上创建UIView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够在某个CGPoint上创建和显示UIView。

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.

然后我以编程方式创建一个UIView,并将它的x和y坐标设置为我从手势识别器获得的CGPoint。

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.

我可以创建它并将其添加为子视图,但创建的UIView的位置与TAP的位置不同。

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子类UIView

AnimationView subclasses UIView

我的代码在下面

    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)

我做错了什么?

推荐答案

你的问题是,您希望视图的中心是您单击的点。目前, UIView 的左上角将是您触及的点。所以试试这个:

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)

如你所见,现在你设置之前的宽度和高度并调整x和y,以便视图的中心是你触摸的点。

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.

但更好的方法是,就像Rob在他提到的那样回答只是将视图的中心设置为您的位置。这样你只需要设置框架的大小并使用 CGSizeMake 而不是 CGRectMake 方法:

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

这篇关于如何在某个CGPoint上创建UIView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆