添加小圆圈/点用户点击UIView(Swift)内部

时间:2016-01-23 23:52:05

标签: xcode swift uiview drawing touchesbegan

我正在试图弄清楚如何在UIView上添加一个小圆圈/点,但仅当用户点击UIView时。点应该放在用户点击的任何地方。遗憾的是,我不知道该怎么做。

任何带代码的示例都非常有用!我正在使用Swift。

1 个答案:

答案 0 :(得分:4)

View Controller 中,您应该首先实现touchesBegan方法,该方法为您提供了一组可以使用的UITouch个对象。然后,每个UITouch对象都有locationInView属性,可以为您提供触摸的CGPoint位置。您可以将这些位置保存在数组中( VC 的属性)。或者,您可以在此方法中立即初始化对象。

func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    for touch in touches{
        let location = (touch as! UITouch).locationInView(self.courtView)
        var dot = UIView(frame: CGRect(location.x, location.y, 10, 10))
        self.courtView.addSubview(dot) //add dot as subview to your main view
        }
    }

您作为[{1}}的参数提供的内容主要取决于您的视图层次结构,可能是locationInViewselfself.contentView。同样适用于将添加为子视图的位置。