Steve
Steve

Reputation: 25

drawRect function not triggered when needDisplay is called

I am trying to create a custom class to build various graph views for the app eventually. The main class is the viewController class where I would like to present the graphs managed by the clGraph class. clGraph class will be used to process the data and create a graph view by vGraph class.

plotGraph function in the vGraphs is where I am struggling. It appears that the drawRect function is not called, however, setNeedsDisplay is called. Below is the test code that I have to understand and learn the basics. Requesting help to be able to draw a basic line on the targetView. Thank you.

class main : NSViewController {
    
    @IBOutlet weak var targetView: NSView!
    
    func plotGraph(){
        let g = clGraphs()
        g.initialize(graphCanvas: targetView, controller: self)
        g.processData()
        g.plotline()
    }
}

class clGraphs {
    
    var controller = NSViewController()
    var graphCanvas = NSView()
    
    var lineData = [Float]()
    
    public func initialize (graphCanvas : NSView, controller : NSViewController) -> clGraphs{
        self.graphCanvas = graphCanvas
        self.controller = controller
        return self
    }
    
    public func plotline(){
        let lb = NSTextField(frame: NSRect(x: 10, y: 10, width: 100, height: 20))
        lb.stringValue = "Test" //works fine on the view
        graphCanvas.addSubview(lb)
        print(graphCanvas.frame) //works fine
        let g = vGraphs()
        g.graphCanvas = graphCanvas
        g.needsDisplay = true
    }
    
    public func processData(){
        //Some logic to update lineData
    }
}

class vGraphs: NSView{
    
    var graphCanvas = NSView()
    var lineData = [Float]()
    
    override func draw(_ dirtyRect: NSRect) {
        print("In the draw rect function")
    }
    
    override func setNeedsDisplay(_ invalidRect: NSRect) {
        print("In the set needs display function")
        plotGraph()
    }
    
    func plotGraph(){
        graphCanvas.layer?.backgroundColor = NSColor.blue.cgColor //works fine
        let aPath = NSBezierPath()
        aPath.move(to: NSPoint(x: 50, y: 50))
        aPath.line(to: NSPoint(x: 200, y: 200))
        aPath.lineWidth = 10
        aPath.close()
        aPath.stroke()
        // ERROR: CGContextRestoreGState: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
    }
}

Upvotes: 0

Views: 67

Answers (0)

Related Questions