Базовый график: добавить легенду в pieChart с «legendTitleForPieChart» не работает - PullRequest
1 голос
/ 05 марта 2012

Я новичок в разработке IOS, и у меня проблема с отрисовкой легенды круговой диаграммы с Core-Plot. Круговая диаграмма хорошо отображается, но не отображает ее легенду.Я уже много читал об этой проблеме ( StackOverFlowResponseTopic ), но не могу понять, почему она не работает со мной.

Я создал PieChartView, который я инициализирую вмой второй ViewController приложения tabBar.

Это код моего представления круговой диаграммы:

//
//  PieChartView.m
//  ExerciceRecap
//
//  Created by Alex on 02/03/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "PieChartView.h"
#import "ModeleDeDonnes.h"
#import "CorePlot-CocoaTouch.h"    

@implementation PieChartView

@synthesize graph=_graph;
@synthesize hostingView = _hostingView;
@synthesize graphData = _graphData;
@synthesize myLabels = _myLabels;    

- (id) initWithHostingView:(CPTGraphHostingView *)hostingView andData:(NSMutableArray *)data{
    self = [super init];

    if (self != nil){
        self.hostingView = hostingView;
        self.graph = nil;

        // Manage data from dataController
        _myLabels = [[[NSMutableArray alloc]init]autorelease];
        NSMutableArray *myValues  = [[[NSMutableArray alloc]init]autorelease];

        for (NSUInteger i = 0; i < [data count]; i++) { 
            ModeleDeDonnes *theObject = [data objectAtIndex:i]; 
            [_myLabels addObject:theObject.nom];
            [myValues addObject:theObject.montant];
        }
        self.graphData = myValues;
    }
    return self;
}

-(void)initialisePieChart{

    if ([_graphData count] == 0 ){
        NSLog(@"No data");
        return;
    }

    if((self.hostingView == nil) || (self.graphData == nil)){
        NSLog(@" Cannot initialse hostingView");
        return;
    }

    if (self.graph != nil){
        NSLog(@" graph already exists");
        return;
    }

    CGRect frame = [self.hostingView bounds];
    self.graph = [[[CPTXYGraph alloc] initWithFrame:frame] autorelease];

    //Tie the graph we have created with the hosting view
    self.hostingView.hostedGraph = self.graph;

    CPTPieChart * pieChart = [[[CPTPieChart alloc]init]autorelease];
    pieChart.dataSource =  self;
    pieChart.pieRadius = 100.0;
    pieChart.identifier = @"pieChart1";
    pieChart.startAngle = M_PI_2;
    pieChart.sliceDirection = CPTPieDirectionCounterClockwise;
    _graph.title=@"My PieChart";    

    // Add legend
    CPTLegend *theLegend = [CPTLegend legendWithGraph:_graph];
    theLegend.numberOfColumns = 2;
    theLegend.fill = [CPTFill fillWithColor:[CPTColor redColor]];
    //theLegend.borderLineStyle = [CPTLineStyle lineStyle];
    theLegend.cornerRadius = 5.0;    
    _graph.legend = theLegend;

    _graph.legendAnchor = CPTRectAnchorBottom;
    _graph.legendDisplacement = CGPointMake(0.0, 30.0);

    [self.graph addPlot:pieChart];

}

-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot{
    return [self.graphData count];
}

-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index{
    return [self.graphData objectAtIndex:index];
}

-(NSString *)legendTitleForPieChart:(CPTPieChart *)pieChart
                        recordIndex:(NSUInteger)index{
    NSLog(@"LegendTitleForPieChart");
   return [NSString stringWithFormat:@"Ma légende", index];        
}

@end

А это код viewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];



   self.pieChart =[[PieChartView alloc] initWithHostingView:_myGraphView     andData:_dataController.masterDataList];
   [self.pieChart initialisePieChart];        
}

Большое спасибо и извините за мой плохой английский.

Ответы [ 2 ]

0 голосов
/ 21 ноября 2014

Попробуйте перезагрузить данные представления хостинга в методе viewWillAppear вашего viewController:

- (void)viewWillAppear:(BOOL)animated
{
   [super viewWillAppear:animated];

   self.pieChart =[[PieChartView alloc] initWithHostingView:_myGraphView     andData:_dataController.masterDataList];
   [self.pieChart initialisePieChart];    

   [self.pieChart.hostingView reloadData];    
}
0 голосов
/ 13 марта 2012

Если вы не можете заставить CorePlot делать то, что вам нужно, вы можете рассмотреть несколько альтернатив:

Каковы альтернативы Core-Plot для рисования графиков в iPhone SDK

Я бы порекомендовал ShinobiCharts лично, но по общему признанию, я предвзятый!Надеюсь, это поможет:)

...