将视图添加到子视图

Add view to subView

我在 xcode 中实现了 core plot。我正在尝试将图例插入另一个 cell。这是我如何实现 legend.

的代码
- (void)configureLegend
{
    CPTGraph *graph = self.hostView.hostedGraph;
    CPTLegend *theLegend = [CPTLegend legendWithGraph:graph];

    // Configure the legend
    theLegend.numberOfColumns = 1;
    theLegend.fill = [CPTFill fillWithColor:[CPTColor whiteColor]];
    theLegend.borderLineStyle = [CPTLineStyle lineStyle];
    theLegend.cornerRadius = 5.0;

    // Add legend to graph
    graph.legend = theLegend;
    graph.legendAnchor = CPTRectAnchorRight;
    CGFloat legendPadding = - (self.chartView.bounds.size.width / 8);
    graph.legendDisplacement = CGPointMake(legendPadding, 0.0);

这是我尝试过的:

    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    [cell addSubview:theLegend];
}

我收到以下错误:

Incompatible pointer types sending 'CPTGraph *' to parameter of type 'UIView *'

我明白错误,以及我做错了什么。我的问题是,如何将 legend 添加为单元格的 subview

编辑

我要说的是:

我想将包含所有信息的部分 - "AAPL" GOOG" "MSFT"(右边的东西)移动到另一个单元格。

使用

CPTGraphHostingView

放置在 UIView 中,

如错误消息所示,您正在尝试将类型不属于 UIView 的对象添加为单元格的子视图。将 CTPGraph 对象添加到类型 CPTGraphHostingView 的实例,然后将其作为子视图添加到单元格:

CPTGraphHostingView *hostingView = [[CPTGraphHostingView alloc] initWithFrame:frame];
hostingView.hostedGraph = graph;

[cell addSubview:hostingView];

此外,您真的不应该那样访问单元格。您应该将图表添加为 UITableView 的委托方法 tableView:cellForRowAtIndexPath: 的子视图。在返回完成的单元格之前,使用此方法检索图例并将其添加到单元格。

已更新 - 您使用的是静态 UITable 视图,因此 cellForRowAtIndexPath: 的实现略有不同。您必须从 super(Table 视图)检索单元格,而不是将可重用单元格出队:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];

    ...retrieve instance of graph...

    CPTGraphHostingView *hostingView = [[CPTGraphHostingView alloc] initWithFrame:frame];
    hostingView.hostedGraph = graph;

    [cell addSubview:hostingView];

    return cell;
}

更新 2 - 仅向单元格添加图例:

[cell.layer addSublayer:graph.legend];

更新 3 - 您的文字可能会颠倒,因为图例图层使用的坐标系可能不同。您可以通过使用变换将图层旋转 180 度来解决此问题:

legendLayer.transform = CATransform3DMakeRotation(M_PI / 180.0f, 0, 1, 0);

因为 CPTGraph * 不是 UIView * 的子类。您需要通过 [cell addSubview:graph.hostingView];

CPTGraphHostingView *hostingView 添加到视图中