Search code examples
iosswiftuiviewsubclasscore-plot

Can't subclass CPTGraphHostingView in CorePlot anymore (v2.3)?


I have just updated my app with the latest release of CorePlot (v2.3, I was running a version < 2.0 previously). I did not get any errors however my graphs have disappeared. I used to subclass CPTGraphHostingView by doing something like:

final class GraphView: CPTGraphHostingView, CPTPlotDataSource {

required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        configureGraph()
        ...
}

fileprivate func configureGraph() {
    // Graph theme
    graph.apply(CPTTheme(named: .plainWhiteTheme))

    // Hosting view
    self.hostedGraph = graph

    // Plot Space
    plotSpace = graph.defaultPlotSpace as! CPTXYPlotSpace
}

I noticed that subclassing a UIView instead of CPTGraphHostingView works with the new release:

final class GraphView: UIView, CPTPlotDataSource {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        configureGraph()
        ...
}

fileprivate func configureGraph() {
    // Graph theme
    graph.apply(CPTTheme(named: .plainWhiteTheme))

    // Hosting view
    let hostingView = CPTGraphHostingView(frame: self.frame)
    hostingView.hostedGraph = graph
    self.addSubview(hostingView)

    // Plot Space
    plotSpace = graph.defaultPlotSpace as! CPTXYPlotSpace
}

It is fine in most of cases, but one of my graph is located on a ScrollView (paging enabled) so getting self.frame for the hostingView in that case is not easy. Am I missing something in this new release? Thanks!


Solution

  • So based on Eric answer, I removed the subclass and simply added constraints to the hosting view:

    fileprivate func configureGraph() {
        // Graph theme
        graph.apply(CPTTheme(named: .plainWhiteTheme))
    
        let hostingView = CPTGraphHostingView(frame: self.bounds)
        hostingView.hostedGraph = self.graph
        self.addSubview(hostingView)
        hostingView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            hostingView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0),
            hostingView.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0),
            hostingView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 1),
            hostingView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 1)
        ])
    
        // Plot Space
        plotSpace = graph.defaultPlotSpace as! CPTXYPlotSpace
    }