我正在试图弄清楚如何在UIView上添加一个小圆圈/点,但仅当用户点击UIView时。点应该放在用户点击的任何地方。遗憾的是,我不知道该怎么做。
任何带代码的示例都非常有用!我正在使用Swift。
答案 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}}的参数提供的内容主要取决于您的视图层次结构,可能是locationInView
,self
或self.contentView
。同样适用于将点添加为子视图的位置。