在用户点击 UIView 内部的任何位置添加小型 Circle/Dot (Swift)
Add Small Circle/Dot Wherever User Taps Inside of UIView (Swift)
我正在尝试弄清楚如何在 UIView 上添加一个小的 circle/dot,但仅当用户点击 UIView 内部时。点应该放在用户点击的任何地方。不幸的是,我不知道该怎么做。
任何带有代码的示例都非常有帮助!我正在使用 Swift.
在您的 View Controller 中,您应该首先实现 touchesBegan
方法,该方法为您提供一个可以使用的 UITouch
对象数组。然后每个 UITouch
对象都有 locationInView
属性,它给你触摸的 CGPoint
位置。您可以将这些位置保存在数组中(VC 的属性)。或者你可以在这个方法中立即初始化你的 dot 对象。
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
}
}
你给 locationInView
的参数主要取决于你的视图层次,它可能是 self
、self.contentView
或 self.view
。这同样适用于将 点 添加为子视图的位置。
我正在尝试弄清楚如何在 UIView 上添加一个小的 circle/dot,但仅当用户点击 UIView 内部时。点应该放在用户点击的任何地方。不幸的是,我不知道该怎么做。
任何带有代码的示例都非常有帮助!我正在使用 Swift.
在您的 View Controller 中,您应该首先实现 touchesBegan
方法,该方法为您提供一个可以使用的 UITouch
对象数组。然后每个 UITouch
对象都有 locationInView
属性,它给你触摸的 CGPoint
位置。您可以将这些位置保存在数组中(VC 的属性)。或者你可以在这个方法中立即初始化你的 dot 对象。
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
}
}
你给 locationInView
的参数主要取决于你的视图层次,它可能是 self
、self.contentView
或 self.view
。这同样适用于将 点 添加为子视图的位置。