当用户点击图表时创建一个 MarkerView

Create a MarkerView when user clicks on Chart

我搜索并搜索了如何在用户使用图表(是 iOS-图表)单击条形图中的条形图时显示 MarkerView Swift。

文档说明库能够 "Highlighting values (with customizable popup-views)" 使用 MarkerViews,但我不知道如何显示。

我想要在用户单击条形图中的条形时显示一个小工具提示,如下图所示。

条形图工具提示:

我已经准备好 chartValueSelected 函数,它会在选择柱形图时触发。

那么您使用的是 Charts 对吗?

你检查过 BallonMarker.swift 了吗?

/ChartsDemo/Classes/Components/BallonMarker.swift

Swift

let marker:BalloonMarker = BalloonMarker(color: UIColor.redColor(), font: UIFont(name: "Helvetica", size: 12)!, insets: UIEdgeInsets(top: 7.0, left: 7.0, bottom: 7.0, right: 7.0))
marker.minimumSize = CGSizeMake(75.0, 35.0)
chartView.marker = marker

Swift 3 次更新

let marker:BalloonMarker = BalloonMarker(color: UIColor.black, font: UIFont(name: "Helvetica", size: 12)!, textColor: UIColor.white, insets: UIEdgeInsets(top: 7.0, left: 7.0, bottom: 7.0, right: 7.0))
marker.minimumSize = CGSize(width: 75.0, height: 35.0)
chartView.marker = marker

Objective-C

BalloonMarker *marker = [[BalloonMarker alloc] initWithColor:[UIColor colorWithRed:14.0/255.0 alpha:1.0] font:[UIFont systemFontOfSize:12.0] insets: UIEdgeInsetsMake(7.0, 7.0, 7.0, 7.0)];
marker.minimumSize = CGSizeMake(75.f, 35.f);
_chartView.marker = marker;

Swift 带有 Objective C 代码的图表库将是这样的。我在这里只是展示一些代码片段。

  1. ChartViewController.m

    -(void)initializeChart {
    
        //chart specifications will go here 
        ...
        ...
    
        //set balloon marker to the chart
        BalloonMarker *marker = [[BalloonMarker alloc]
                         initWithColor: kColorBrown1
                         font: [UIFont systemFontOfSize:12.0]
                         textColor: UIColor.whiteColor
                         insets: UIEdgeInsetsMake(8.0, 8.0, 20.0, 8.0)];
        marker.chartView = chartView;
        marker.minimumSize = CGSizeMake(80.f, 40.f);
        chartView.marker = marker;
    }
    
  2. BalloonMarker.swift

    import Charts
    
    ...
    
    ...
    
    //This method will be called when ever user clicks on a chart to refresh the marker text. You need to specify the value here.
    
    open override func refreshContent(entry: ChartDataEntry, highlight: Highlight)
    
    {  
        setLabel(entry.y!)        
    }
    

即使在将 BalloonMarker 添加到图表后,如果未显示标记,请确保在图表视图中启用标记

chartView.drawMarkers = true

在图表数据集上启用了突出显示。这应该在您分配图表数据集后完成。

chartView.data?.highlightEnabled = true