Search code examples
iosswiftcore-graphicsuibezierpath

Swift : drawing the dots in loop


I am trying to draw multiple dots in a loop by passing set of points. But not a single dot is getting drawn on view. Idea - I am parsing xml document and extracting point to draw it on view.

   Edit - I have updated the code with suggested changes and it is working. 

            //View Class
            class DrawTrace: UIView
{

    var points = [CGPoint]()
    {
        didSet {
            setNeedsDisplay()
        }
    }

override  func draw(_ rect: CGRect)
    {
        let size = CGSize(width: 1, height: 1)
        UIColor.white.set()
        for point in points
        {
            print(point.x,point.y)
            let dot = UIBezierPath(ovalIn: CGRect(origin: point, size: size))

            dot.fill()
        }
    }



}
 //View Controller Class  

    class ViewController: UIViewController
    {
        var object : traceDoc =  traceDoc()
        let trace = DrawTrace(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
        override func viewDidLoad()
        {

            super.viewDidLoad()
            object.collectionOfData()
            trace.points = object.tracePoints
            self.view.addSubview(trace)
        }
    }

Added view instance to view hierarchy that is in view controller.Created instance of DrawTrace and appended to tracepoints array.


Solution

  • Your code is way more complex than it needs to be. One big issue is that you keep adding more and more layers each time draw is called.

    There is no need to use layers to draw dots in your custom view. Here is a much simpler solution:

    class DrawTrace: UIView
    {
        var points = [CGPoint]() {
            didSet {
                setNeedsDisplay()
            }
        }
    
        override func draw(_ rect: CGRect)
        {
            let size = CGSize(width: 2, height: 2)
    
            UIColor.black.set()
            for point in points {
                let dot = UIBezierPath(ovalIn: CGRect(origin: point, size: size))
                // this just draws the circle by filling it.
                // Update any properties of the path as needed.
                // Use dot.stroke() if you need an outline around the circle.
                dot.fill()
            }
        }
    }
    
    let trace = DrawTrace(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    trace.backgroundColor = .white
    trace.points = [ CGPoint(x: 10, y: 10), CGPoint(x: 35, y: 100)]
    

    The above can be copied into a playground.