Objective c 将CorePlot条形图添加到子视图

Objective c 将CorePlot条形图添加到子视图,objective-c,uiview,core-plot,cptbarplot,Objective C,Uiview,Core Plot,Cptbarplot,目前,我正在使用Coreplot的图形框架来实现条形图 我从中提取了教程项目 我稍微修改了教程,以提取web服务数据,而不是静态数据 现在,当我将视图加载到视图控制器中时,一切都很好-条形图完美地显示了所有内容 另外,我在示例中使用散点图,对数据拉入的web服务数据执行相同的操作,并在其自己的视图控制器中显示该图 现在,我想将散点图和条形图添加到视图控制器的子视图中 理解这两个都可以在viewcontroller中查看,其子类是UINavigationController(希望我的术语是正确的:

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

我从中提取了教程项目

我稍微修改了教程,以提取web服务数据,而不是静态数据

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

另外,我在示例中使用散点图,对数据拉入的web服务数据执行相同的操作,并在其自己的视图控制器中显示该图

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

理解这两个都可以在viewcontroller中查看,其子类是UINavigationController(希望我的术语是正确的:/)

无论如何,我能够在子视图中显示散点图。。。。没问题

但最令人沮丧的是每当我对条形图做同样的事情时。。。砰的一声,砰的一声

当我在条形图视图中添加条形图时,它崩溃了

        [graph addPlot:plot toPlotSpace:graph.defaultPlotSpace];
没有这条线。。。应用程序正在运行,但看不到任何条

现在,我不会将图形添加到我的子视图,而是转到视图控制器,在那里它显示图形,不会崩溃。。。。但是,在我将条形图添加到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

经过几天的等待和Coreplot成员的帮助。。。。问题解决了

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

在我为CPTBarplot分配并实例化空间之后添加这一行代码

[barplot.datasource retain];
一行代码总是有用的:)


这让我的一天在我的子视图中看到我的图形。。。。现在,为了使轴看起来更漂亮……

需要等待几天,并得到Coreplot成员的帮助。。。。问题解决了

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

在我为CPTBarplot分配并实例化空间之后添加这一行代码

[barplot.datasource retain];
一行代码总是有用的:)


这让我的一天在我的子视图中看到我的图形。。。。现在,为了使轴看起来更美观……

图形可能正在尝试在完全设置之前从
graphData
中提取数据。你能得到堆栈跟踪吗?如果将日志记录语句添加到数据源方法,将打印什么?图形可能在完全设置之前试图从
graphData
中提取数据。你能得到堆栈跟踪吗?如果向datasource方法添加日志语句,将打印什么?