【问题标题】:How can I create a UIView at a certain CGPoint?如何在某个 CGPoint 创建 UIView?
【发布时间】:2015-04-23 23:18:47
【问题描述】:

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

到目前为止,我有一个手势识别器,它作为子视图添加到主视图中。

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

我可以创建它并将其添加为子视图,但创建的 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)

是不是我做错了什么?

【问题讨论】:

  • 不同是什么意思?完全是另一个位置或附近?
  • 事实证明,经过仔细检查,它会在水龙头的位置创建左角的视图。我猜这是水龙头的 x + y 坐标。如何使视图直接在水龙头的中心产生。

标签: ios swift uiview cgpoint


【解决方案1】:

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

 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

【讨论】:

    【解决方案2】:

    只需设置它的center:

    animationImage.center = tappedLocation
    

    【讨论】:

    • 不知道。比仅使用计算中点更好的方法。 +1
    【解决方案3】:

    让我们创建一个点击手势并将其分配给一个视图

    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
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      • 1970-01-01
      • 2016-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      相关资源
      最近更新 更多