-
Notifications
You must be signed in to change notification settings - Fork 0
iOS Chart Library 實作 Manual
Kuan L. Chen edited this page Dec 14, 2015
·
1 revision
然而我們可以將 iOS Chart Library 下載下來,這個 zip 檔包含了函式庫(在檔案夾裡稱為 Charts),將此函式庫複製到專案根目錄上,並在 Finder 打開此函式庫資料夾,拖曳 Charts.xcodeproj 至 Xcode 專案中。 如下圖所示。
![1](https://github.com/25sprout/ChartLib-Demo-iOS/blob/master/iOS%20Chart%20Demo%20by%2025sprout/Pic%20Resources/1.png?raw=true)
接下來,從你的 Project Navigator 選取你的專案,在右邊的 General 鍵,至 Embedded Binary 區塊,按 + 並加入 Charts 框架。從清單選取 Charts.framwork 並 Add。
![2](https://github.com/25sprout/ChartLib-Demo-iOS/blob/master/iOS%20Chart%20Demo%20by%2025sprout/Pic%20Resources/2.png?raw=true)
@import Charts;
接下來拖曳一個視圖(View)至 Storyboard,並至 Identity Inspector 將類別設為 BarChartView。加入視圖的 outlet 至 ViewController 類別。
@property (weak, nonatomic) IBOutlet BarChartView *barChartView;
![3](https://github.com/25sprout/ChartLib-Demo-iOS/blob/master/iOS%20Chart%20Demo%20by%2025sprout/Pic%20Resources/3.png?raw=true)
_barChartView.noDataText = @"你客製化的訊息";
_barChartView.noDataTextDescription = @"更多詳情";
@property (strong, nonatomic) NSArray *months;
@property (strong, nonatomic) NSArray *unitsSolds;
months = @[@"Jan", @"Feb", @"Mar", @"Apr", @"May", @"Jun", @"Jul", @"Aug", @"Sep", @"Oct", @"Nov", @"Dec"];
unitsSolds = @[@20.0f, @4.0f, @6.0f, @3.0f, @12.0f, @16.0f, @4.0f, @18.0f, @2.0f, @4.0f, @5.0f, @4.0f];
NSMutableArray *dataEntries = [[NSMutableArray alloc]init];
以 months 的數量透過迴圈讀取 unitsSolds 相對應的數值,再透過 BarChartDataEntry 將 unitsSolds 數值實體化並對應months & unitsSolds,最後再將 BarChartDataEntry 加入至已經建立好的 NSMutableArray。
for ( int i = 0; i < months.count; i++) {
double unitSold = [[unitsSolds objectAtIndex:i]doubleValue];
BarChartDataEntry *dataEntry = [[BarChartDataEntry alloc] initWithValue:unitSold xIndex:i];
[dataEntries addObject:dataEntry];
}
BarChartDataSet *chartDataSet = [[BarChartDataSet alloc] initWithYVals:dataEntries label:@"Unit Sold"];
BarChartData *chartData = [[BarChartData alloc] initWithXVals:months dataSet:chartDataSet];
_barChartView.data = chartData;
最後別忘了再將 LineChartData 放在 lineChartView 中哦~ (倘若你是直接建立 Line Chart 而不想沿用 Bar Chart 的資料,建立 Data 的語法則是 ChartDataEntry,但在這邊請注意,Bar Chart 不可以使用 ChartDataEntry 語法,否則會出現錯誤,原因可能是 Bar Chart 是一整條的在 UI 上畫出來,不像 Line Chart 是以點對點的連線顯示)
![5](https://github.com/25sprout/ChartLib-Demo-iOS/blob/master/iOS%20Chart%20Demo%20by%2025sprout/Pic%20Resources/5.png?raw=true)