我怎样才能创build一个特定的CGPoint的UIView?
我需要能够创build和显示一个特定的CGPoint的UIView。
到目前为止,我有一个手势识别器,作为子视图添加到主视图。
然后我编程创build一个UIView,并设置它的x和y坐标到我从手势识别器获得的CGPoint。
我能够创build它并将其添加为子视图,但创build的UIView的位置不同于TAP的位置。
AnimationView子类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
左上angular将是你触及的点。 所以试试看:
var frameSize:CGFloat = 64 animationImage.frame = CGRectMake(tappedLocation.x - frameSize/2, tappedLocation.y - frameSize/2, frameSize, frameSize)
如您所见,现在您先设置宽度和高度,然后调整x和y,使视图的中心位置成为您触摸的点。
但更好的办法就像Rob在他的回答中提到的那样,只是把视图的中心设置在你的位置上。 这样,你只需要设置你的框架的大小,并使用CGSizeMake
而不是CGRectMake
方法:
animationImage.frame.size = CGSizeMake(100, 100) animationImage.center = tappedLocation
只需设置其center
:
animationImage.center = tappedLocation
让我们创build一个Tap Gesture并将其分配给一个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)
每次使用指定的“轻击手势”点击视图时,都会调用此函数。
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 }