Search code examples
xcodeswiftuiviewdrawingtouchesbegan

Add Small Circle/Dot Wherever User Taps Inside of UIView (Swift)


I'm trying to figure out how to add a small circle/dot on a UIView but only when the user taps inside of the UIView. The dot should be placed wherever the user taps. I, unfortunately have no idea how to do this.

Any examples with code are very helpful! I'm using Swift.


Solution

  • In your View Controller you should first implement touchesBegan method which gives you an array of UITouch objects that you can work with. Then each UITouch object has locationInView property which gives you the CGPoint location of the touch. You can save those locations in an array (attribute of your VC). Or you can initialize your dot object right away in this method.

    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
            }
        }
    

    What you give as an argument to locationInView mainly depends on your view hierarchy, it may be self, self.contentView or self.view. Same applies to where you add your dot as a subview.