1

目前,我正在使用 Coreplot 的图形框架来实现条形图。

我从http://www.raywenderlich.com/13271/how-to-draw-graphs-with-core-plot-part-2中提取了教程项目。

我稍微更改了教程以提取 Web 服务数据而不是静态数据。

现在,当我将视图加载到视图控制器中时,一切都很好——条形图完美地显示了一切。

此外,我在示例中使用了散点图,对数据进行了相同的处理 - 提取 Web 服务数据,并在其自己的视图控制器中显示该图。

现在,我想将散点图和条形图都添加到视图控制器的子视图中。

了解两者都可以在其子类为 UINavigationController 的视图控制器中查看(希望我的术语是正确的:/)。

无论如何,我可以在子视图中显示 SCATTER PLOT 图....没问题....

但最令人沮丧的部分是每当我对条形图做同样的事情时...... BOOM CRASH CRASH CRASH !!!!

它在我将条形图添加到条形图视图的行上崩溃...

        [graph addPlot:plot toPlotSpace:graph.defaultPlotSpace];

没有这条线...应用程序运行但看不到任何条形...

现在我没有将图表添加到我的子视图中,而是转到显示图表的视图控制器,没有崩溃......但是在我将 BAR GRAPH 添加到更多内容所在的 uiviewcontroller 的子视图中。 ...崩溃崩溃崩溃...

让我如此沮丧的是散点图的一切都很好......不是条形图......

如果需要,我会提供更多信息....我只想知道如何将条形图添加到 uiview

这就是我所做的......

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 140, 320, 150)];
view.backgroundColor = [UIColor clearColor];
[scroller addSubview:view];

_0DGraphViewController *BarGraphView = [[_0DGraphViewController alloc] init];
BarGraphView.hostView.frame = CGRectMake(view.bounds.origin.x, view.bounds.origin.y, view.bounds.size.width , view.bounds.size.height);
[view addSubview:BarGraph.view];

这是我的条形图类

#import "30DGraphViewController.h"
#define graphData30DRequest [NSURL URLWithString:url]

@implementation _0DGraphViewController

@synthesize hostView = hostView_;

@synthesize priceAnnotation = priceAnnotation_;

CGFloat const _0DBarWidth = 0.25f;
CGFloat const _0DBarInitialX = 0.25f;

-(void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - UIViewController lifecycle methods
//-(void)viewDidAppear:(BOOL)animated {

//    [super viewDidAppear:animated];

//}

- (void)viewDidLoad
{

    //[super viewDidLoad];

    graphData = [[PullEasyViewData alloc] init];



    SWRevealViewController *revealController = [self revealViewController];

    [self.navigationController.navigationBar addGestureRecognizer:revealController.panGestureRecognizer];

    UIBarButtonItem *revealButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"reveal-icon.png"]
                                                                         style:UIBarButtonItemStyleBordered target:revealController action:@selector(revealToggle:)];

    self.navigationItem.leftBarButtonItem = revealButtonItem;

    UIBarButtonItem *rightRevealButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"reveal-icon.png"]
                                                                              style:UIBarButtonItemStyleBordered target:revealController action:@selector(rightRevealToggle:)];

    self.navigationItem.rightBarButtonItem = rightRevealButtonItem;


    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *startDate = @"20130514";
        NSString *endDate = @"20130613";

        NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
        [graphData performSelectorOnMainThread:@selector(fetchGraphDataRequestData30D:) withObject:data waitUntilDone:YES];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self initPlot];
        });

    });
}

#pragma mark - Rotation
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}

#pragma mark - Chart behavior
-(void)initPlot {
    self.hostView.allowPinchScaling = NO;
    [self configureHost];
    [self configureGraph];
    [self configurePlots];
    [self configureAxes];
}

-(void)configureHost {
    //self.hostView = [(CPTGraphHostingView *) [CPTGraphHostingView alloc] initWithFrame:self.view.bounds];
    self.hostView = [(CPTGraphHostingView *) [CPTGraphHostingView alloc] initWithFrame:CGRectMake(0, 0, 320, 170)];

    self.hostView.allowPinchScaling = YES;
    [self.view addSubview:self.hostView];
}

-(void)configureGraph {
    // 1 - Create the graph
    CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:self.hostView.bounds];
    graph.plotAreaFrame.masksToBorder = NO;
    self.hostView.hostedGraph = graph;

    // 2 - Configure the graph
    [graph applyTheme:[CPTTheme themeNamed:kCPTPlainBlackTheme]];
    graph.paddingBottom = 30.0f;
    graph.paddingLeft  = 30.0f;
    graph.paddingTop    = -1.0f;
    graph.paddingRight  = -5.0f;

    // 3 - Set up styles
    CPTMutableTextStyle *titleStyle = [CPTMutableTextStyle textStyle];
    titleStyle.color = [CPTColor whiteColor];
    titleStyle.fontName = @"Helvetica-Bold";
    titleStyle.fontSize = 16.0f;

    // 4 - Set up title
    NSString *title = @"Portfolio Prices: April 23 - 27, 2012";
    graph.title = title;
    graph.titleTextStyle = titleStyle;
    graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
    graph.titleDisplacement = CGPointMake(0.0f, -16.0f);

    // 5 - Set up plot space
    CGFloat xMin = 0.0f;
    CGFloat xMax = [[graphData getGraphDates30D] count];//[[[CPDStockPriceStore sharedInstance] datesInWeek] count];
    CGFloat yMin = 0.0f;
    CGFloat yMax = 20.0f;  // should determine dynamically based on max price
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(xMin) length:CPTDecimalFromFloat(xMax)];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(yMin) length:CPTDecimalFromFloat(yMax)];
}

-(void)configurePlots {

    // 1 - Set up the three plots
    CPTBarPlot *aaplPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor redColor] horizontalBars:NO];
    aaplPlot.identifier = CPDTickerSymbolAAPL;
    //CPTBarPlot *googPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor greenColor] horizontalBars:NO];
    //googPlot.identifier = CPDTickerSymbolGOOG;
    //CPTBarPlot *msftPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor blueColor] horizontalBars:NO];
    //msftPlot.identifier = CPDTickerSymbolMSFT;

    // 2 - Set up line style
    CPTMutableLineStyle *barLineStyle = [[CPTMutableLineStyle alloc] init];
    barLineStyle.lineColor = [CPTColor lightGrayColor];
    barLineStyle.lineWidth = 0.5;

    // 3 - Add plots to graph
    CPTGraph *graph = self.hostView.hostedGraph;
    CGFloat barX = _0DBarInitialX;
    //NSArray *plots = [NSArray arrayWithObjects:aaplPlot, googPlot, msftPlot, nil];
    NSArray *plots = [NSArray arrayWithObjects:aaplPlot, nil];
    for (CPTBarPlot *plot in plots) {
        plot.dataSource = self;
        plot.delegate = self;
        plot.barWidth = CPTDecimalFromDouble(_0DBarWidth);
        plot.barOffset = CPTDecimalFromDouble(barX);
        plot.lineStyle = barLineStyle;
        [graph addPlot:plot toPlotSpace:graph.defaultPlotSpace];
        barX += _0DBarWidth;
    }
}

-(void)configureAxes {

    // 1 - Configure styles
    CPTMutableTextStyle *axisTitleStyle = [CPTMutableTextStyle textStyle];
    axisTitleStyle.color = [CPTColor whiteColor];
    axisTitleStyle.fontName = @"Helvetica-Bold";
    axisTitleStyle.fontSize = 12.0f;
    CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
    axisLineStyle.lineWidth = 2.0f;
    axisLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:1];

    // 2 - Get the graph's axis set
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *) self.hostView.hostedGraph.axisSet;

    // 3 - Configure the x-axis
    axisSet.xAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
    axisSet.xAxis.title = @"Days of Week (Mon - Fri)";
    axisSet.xAxis.titleTextStyle = axisTitleStyle;
    axisSet.xAxis.titleOffset = 10.0f;
    axisSet.xAxis.axisLineStyle = axisLineStyle;

    // 4 - Configure the y-axis
    axisSet.yAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
    axisSet.yAxis.title = @"Price";
    axisSet.yAxis.titleTextStyle = axisTitleStyle;
    axisSet.yAxis.titleOffset = 5.0f;
    axisSet.yAxis.axisLineStyle = axisLineStyle;
}

-(void)hideAnnotation:(CPTGraph *)graph {
    if ((graph.plotAreaFrame.plotArea) && (self.priceAnnotation)) {
        [graph.plotAreaFrame.plotArea removeAnnotation:self.priceAnnotation];
        self.priceAnnotation = nil;
    }
}

#pragma mark - CPTPlotDataSource methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
    //return [[[CPDStockPriceStore sharedInstance] datesInWeek] count];

    return [[graphData getGraphDates30D] count];
}

-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
    //if ((fieldEnum == CPTBarPlotFieldBarTip) && (index < [[[CPDStockPriceStore sharedInstance] datesInWeek] count])) {
    if ((fieldEnum == CPTBarPlotFieldBarTip) && (index < [[graphData getGraphDates30D] count])) {
        if ([plot.identifier isEqual:CPDTickerSymbolAAPL]) {

            return [[graphData getGraphValues30D] objectAtIndex:index];
            //return [[[CPDStockPriceStore sharedInstance] weeklyPrices:CPDTickerSymbolAAPL] objectAtIndex:index];
        } else if ([plot.identifier isEqual:CPDTickerSymbolGOOG]) {
            //return [[[CPDStockPriceStore sharedInstance] weeklyPrices:CPDTickerSymbolGOOG] objectAtIndex:index];
        } else if ([plot.identifier isEqual:CPDTickerSymbolMSFT]) {
            //return [[[CPDStockPriceStore sharedInstance] weeklyPrices:CPDTickerSymbolMSFT] objectAtIndex:index];
        }
    }
    return [NSDecimalNumber numberWithUnsignedInteger:index];
}

#pragma mark - CPTBarPlotDelegate methods
-(void)barPlot:(CPTBarPlot *)plot barWasSelectedAtRecordIndex:(NSUInteger)index {

    // 1 - Is the plot hidden?
    if (plot.isHidden == YES) {
        return;
    }

    // 2 - Create style, if necessary
    static CPTMutableTextStyle *style = nil;
    if (!style) {
        style = [CPTMutableTextStyle textStyle];
        style.color= [CPTColor yellowColor];
        style.fontSize = 16.0f;
        style.fontName = @"Helvetica-Bold";
    }

    // 3 - Create annotation, if necessary
    NSNumber *price = [self numberForPlot:plot field:CPTBarPlotFieldBarTip recordIndex:index];
    if (!self.priceAnnotation) {
        NSNumber *x = [NSNumber numberWithInt:0];
        NSNumber *y = [NSNumber numberWithInt:0];
        NSArray *anchorPoint = [NSArray arrayWithObjects:x, y, nil];
        self.priceAnnotation = [[CPTPlotSpaceAnnotation alloc] initWithPlotSpace:plot.plotSpace anchorPlotPoint:anchorPoint];
    }

    // 4 - Create number formatter, if needed
    static NSNumberFormatter *formatter = nil;
    if (!formatter) {
        formatter = [[NSNumberFormatter alloc] init];
        [formatter setMaximumFractionDigits:2];
    }

    // 5 - Create text layer for annotation
    NSString *priceValue = [formatter stringFromNumber:price];
    CPTTextLayer *textLayer = [[CPTTextLayer alloc] initWithText:priceValue style:style];
    self.priceAnnotation.contentLayer = textLayer;

    // 6 - Get plot index based on identifier
    NSInteger plotIndex = 0;
    if ([plot.identifier isEqual:CPDTickerSymbolAAPL] == YES) {
        plotIndex = 0;
    } else if ([plot.identifier isEqual:CPDTickerSymbolGOOG] == YES) {
        plotIndex = 1;
    } else if ([plot.identifier isEqual:CPDTickerSymbolMSFT] == YES) {
        plotIndex = 2;
    }

    // 7 - Get the anchor point for annotation
    CGFloat x = index + _0DBarInitialX + (plotIndex * _0DBarWidth);
    NSNumber *anchorX = [NSNumber numberWithFloat:x];
    CGFloat y = [price floatValue] + 40.0f;
    NSNumber *anchorY = [NSNumber numberWithFloat:y];
    self.priceAnnotation.anchorPlotPoint = [NSArray arrayWithObjects:anchorX, anchorY, nil];

    // 8 - Add the annotation
    [plot.graph.plotAreaFrame.plotArea addAnnotation:self.priceAnnotation];
}

@end

请帮忙!!!!散点图类在添加到 uiviewcontroller 中的 uiview 时起作用.....但不是这个条形图!!!!

编辑

崩溃没有给我除此之外的任何信息

0x1a3209f:  movl   (%edi), %esi Thread 1: EXC_BAD_ACCESS (code=1, address=0x5489c855)
4

1 回答 1

1

经过几天的等待和Coreplot成员的一些帮助......问题得到了解决......

显然,对于条形图,我必须确保在图表生命周期的整个生命周期中都不会发布图表......

在我为 CPTBarplot 分配和实例化空间后添加这一行代码确保了这样,

[barplot.datasource retain];

一行代码总是有帮助:).....

这让我一天在我的子视图中看到我的图表......现在让轴看起来不错......

于 2013-06-18T15:29:28.913 回答