{"id":125,"date":"2020-04-13T00:57:24","date_gmt":"2020-04-12T22:57:24","guid":{"rendered":"https:\/\/mic.st\/blog\/?p=125"},"modified":"2023-05-15T21:36:06","modified_gmt":"2023-05-15T19:36:06","slug":"draw-graphs-easily-with-carekits-ockcartesianchartview","status":"publish","type":"post","link":"https:\/\/mic.st\/blog\/draw-graphs-easily-with-carekits-ockcartesianchartview\/","title":{"rendered":"Draw graphs and charts in Swift easily with CareKit"},"content":{"rendered":"\n<p>Did you ever want to use Swift to draw simple graphs and charts in your iOS app without using some 3rd party library? Also you did not want to reinvent the wheel with CoreGraphics? I thought that was not possible until I found out about a really nice open source SDK owned by Apple that you can use for that.<\/p>\n\n\n\n<p>Here comes <strong>CareKit<\/strong>! <a href=\"https:\/\/developer.apple.com\/documentation\/carekit\" target=\"_blank\" rel=\"noopener\">https:\/\/developer.apple.com\/documentation\/carekit<\/a><\/p>\n\n\n\n<p>Are you looking for how to draw graphs in SwiftUI? Check my other blog post: <a href=\"https:\/\/mic.st\/blog\/draw-line-graphs-in-swiftui\/\">https:\/\/mic.st\/blog\/draw-line-graphs-in-swiftui\/<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">A (very) short introduction to CareKit<\/h2>\n\n\n\n<p>CareKit is an open source SDK by Apple that was intended for the use in health management apps. Of course, you do not have to develop a health management app to use it. You can use it for just anything \u2600\ufe0f! One cool thing about the SDK: The owners of the repository splitted it up into several packages so you if you just want to draw nice looking user interfaces with the SDK you do not need to import the whole thing \ud83d\udc4d.<\/p>\n\n\n\n<p>I played around with the graph drawing functionality recently which I want to present to you in this quick overview. I really like it because firstly it is looking nice and secondly it is really easy to use. The following image shows a line graph you can draw pretty quickly with some self explanatory methods.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"266\" height=\"198\" src=\"https:\/\/mic.st\/blog\/wp-content\/uploads\/2020\/04\/grafik.png\" alt=\"Line graphs drawn with Swift using CareKit's OCKCartesianChartView.\" class=\"wp-image-126\"\/><figcaption class=\"wp-element-caption\">Fancy stuff like this \ud83c\udf08<\/figcaption><\/figure>\n\n\n\n<p>You basically just throw in an array of points and the <code>OCKGraphView<\/code> does all the heavy lifting for you. You can give your graphs colors (and gradients \ud83c\udf08!), animations and labels and you can change the type of graph (line, bar, scatterplot) with a keystroke. So what else do you want? This is great stuff \ud83e\udd73<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Get the dependencies<\/h2>\n\n\n\n<p>If you install XCode you cannot instantly use CareKit because it is not delivered with XCode. Thanks to Swift Package Manager you can easily add the git repository to add it to your project. <\/p>\n\n\n\n<p>The official git repo for CareKit is: <code>https:\/\/github.com\/carekit-apple\/CareKit<\/code> To add it to your project via Swift PM, just click in your open project on <em>File-&gt; Swift Packages -&gt; Add Package Dependency<\/em> and copy the link above inside the input field. <\/p>\n\n\n\n<p>The repository owners splitted up CareKit into several packages. So if you just want to use the graphs, you just need to import <code>CareKitUI<\/code>.<\/p>\n\n\n\n<p>For drawing a graph you can use <code>OCKCartesianChartView<\/code> that draws the graph on a card like element and gives you also a some views around the actual graph (e.g. a <code>contentStackView<\/code>, labels and a header).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Let&#8217;s draw some graphs in Swift!<\/h2>\n\n\n\n<p>Let&#8217;s draw two line graphs with random data and some colors:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Swift\" data-shcb-language-slug=\"swift\"><span><code class=\"hljs language-swift\"><span class=\"hljs-keyword\">let<\/span> chart = <span class=\"hljs-type\">OCKCartesianChartView<\/span>(type: .line)  \n\n<span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">func<\/span> <span class=\"hljs-title\">setupChart<\/span><span class=\"hljs-params\">()<\/span><\/span> {\n    <span class=\"hljs-comment\">\/\/\/ First create an array of CGPoints that you will use to generate your data series.<\/span>\n    <span class=\"hljs-comment\">\/\/\/ We use the handy map method to generate some random points.<\/span>\n    <span class=\"hljs-keyword\">let<\/span> dataPoints = <span class=\"hljs-type\">Array<\/span>(<span class=\"hljs-number\">0<\/span>...<span class=\"hljs-number\">20<\/span>).<span class=\"hljs-built_in\">map<\/span> { <span class=\"hljs-number\">_<\/span> <span class=\"hljs-keyword\">in<\/span> <span class=\"hljs-type\">CGPoint<\/span>(x: <span class=\"hljs-type\">CGFloat<\/span>.random(<span class=\"hljs-keyword\">in<\/span>: <span class=\"hljs-number\">0<\/span>...<span class=\"hljs-number\">20<\/span>),\n                                                      y: <span class=\"hljs-type\">CGFloat<\/span>.random(<span class=\"hljs-keyword\">in<\/span>: <span class=\"hljs-number\">1<\/span>...<span class=\"hljs-number\">5<\/span>)) }\n\n    <span class=\"hljs-comment\">\/\/\/ Now you create an instance of `OCKDataSeries` from your array of points, give it a title and a color. The title is used for the label below the graph (just like in Microsoft Excel)<\/span>\n    <span class=\"hljs-keyword\">var<\/span> data = <span class=\"hljs-type\">OCKDataSeries<\/span>(dataPoints: dataPoints,\n                             title: <span class=\"hljs-string\">\"Random stuff\"<\/span>,\n                             color: .green)\n\n    <span class=\"hljs-comment\">\/\/\/ You can create as many data series as you like \ud83c\udf08<\/span>\n    <span class=\"hljs-keyword\">let<\/span> dataPoints2 = <span class=\"hljs-type\">Array<\/span>(<span class=\"hljs-number\">0<\/span>...<span class=\"hljs-number\">20<\/span>).<span class=\"hljs-built_in\">map<\/span> { <span class=\"hljs-number\">_<\/span> <span class=\"hljs-keyword\">in<\/span> <span class=\"hljs-type\">CGPoint<\/span>(x: <span class=\"hljs-type\">CGFloat<\/span>.random(<span class=\"hljs-keyword\">in<\/span>: <span class=\"hljs-number\">0<\/span>...<span class=\"hljs-number\">20<\/span>),\n                                                       y: <span class=\"hljs-type\">CGFloat<\/span>.random(<span class=\"hljs-keyword\">in<\/span>: <span class=\"hljs-number\">1<\/span>...<span class=\"hljs-number\">5<\/span>)) }\n    <span class=\"hljs-keyword\">var<\/span> data2 = <span class=\"hljs-type\">OCKDataSeries<\/span>(dataPoints: dataPoints2,\n                              title: <span class=\"hljs-string\">\"Other random stuff\"<\/span>,\n                              color: .red)\n\n    <span class=\"hljs-comment\">\/\/\/ Set the pen size for the data series...<\/span>\n    data.size = <span class=\"hljs-number\">2<\/span>\n    data2.size = <span class=\"hljs-number\">1<\/span>\n\n    <span class=\"hljs-comment\">\/\/\/ ... and gradients if you like. <\/span>\n    <span class=\"hljs-comment\">\/\/\/ Gradients and colors will be used for the graph as well as the color indicator of your label that shows the title of your data series.<\/span>\n    data.gradientStartColor = .blue\n    data.gradientEndColor = .red\n\n    <span class=\"hljs-comment\">\/\/\/ Finally you add the prepared data series to your graph view.<\/span>\n    chart.graphView.dataSeries = &#91;data, data2]\n\n    <span class=\"hljs-comment\">\/\/\/ If you do not specify the minimum and maximum of your graph, `OCKCartesianGraphView` will take care of the right scaling.<\/span>\n    <span class=\"hljs-comment\">\/\/\/ This can be helpful if you do not know the range of your values but it makes it more difficult to animate the graphs.<\/span>\n    chart.graphView.yMinimum = <span class=\"hljs-number\">0<\/span>\n    chart.graphView.yMaximum = <span class=\"hljs-number\">6<\/span>\n    chart.graphView.xMinimum = <span class=\"hljs-number\">0<\/span>\n    chart.graphView.xMaximum = <span class=\"hljs-number\">10<\/span>\n\n    <span class=\"hljs-comment\">\/\/\/ You can also set an array of strings to set custom labels on the x-axis.<\/span>\n    <span class=\"hljs-comment\">\/\/\/ I am not sure if that works on the y-axis as well.<\/span>\n    chart.graphView.horizontalAxisMarkers = &#91;<span class=\"hljs-string\">\"123\"<\/span>, <span class=\"hljs-string\">\"hello\"<\/span>]\n\n    <span class=\"hljs-comment\">\/\/\/ With theses properties you can set a title and a subtitle for your graph.<\/span>\n    chart.headerView.titleLabel.text = <span class=\"hljs-string\">\"Hello\"<\/span>\n    chart.headerView.detailLabel.text = <span class=\"hljs-string\">\"I am a graph\"<\/span>\n  }<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Swift<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">swift<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The SDK animates your graphs automatically if you add new data to the <code>OCKCartesianGraphView<\/code>. You do not even have to wrap your code into <code>UIView.animate()<\/code> blocks. Let&#8217;s see an example:<\/p>\n\n\n\n<p>If you set <code>chart.graphView.dataSeries = [data, data2]<\/code> on a <code>OCKCartesianGraphView<\/code> that is already presented in your view hierarchy, everything gets animated automatically \ud83d\ude03<\/p>\n\n\n\n<figure class=\"wp-block-video\"><video controls src=\"https:\/\/mic.st\/blog\/wp-content\/uploads\/2020\/04\/Bildschirmvideo-aufnehmen-2020-04-12-um-23.24.42.mov\"><\/video><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Final thoughts on drawing graphs or charts in Swift<\/h2>\n\n\n\n<p>I think this is a really nice API if you want to quickly show some data. Whenever I wanted to draw some graphs or charts with Swift before, I used Core Graphics for that. However, if you go down that rabbit hole you have to rebuilt a lot of stuff that is already there when using the <code>OCKCartesianGraphView<\/code>. I am very curious about using it in some of my current projects. For example, I could think about using it in my vocabulary app for visualizing learner&#8217;s progress.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Did you ever want to use Swift to draw simple graphs and charts in your iOS app without using some 3rd party library? Also you did not want to reinvent the wheel with CoreGraphics? I thought that was not possible until I found out about a really nice open source SDK owned by Apple that&hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[3],"tags":[24,26,25,27,35],"class_list":["post-125","post","type-post","status-publish","format-standard","hentry","category-ios-development","tag-carekit","tag-chartview","tag-graphics","tag-graphview","tag-swift"],"_links":{"self":[{"href":"https:\/\/mic.st\/blog\/wp-json\/wp\/v2\/posts\/125","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/mic.st\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mic.st\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mic.st\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mic.st\/blog\/wp-json\/wp\/v2\/comments?post=125"}],"version-history":[{"count":2,"href":"https:\/\/mic.st\/blog\/wp-json\/wp\/v2\/posts\/125\/revisions"}],"predecessor-version":[{"id":735,"href":"https:\/\/mic.st\/blog\/wp-json\/wp\/v2\/posts\/125\/revisions\/735"}],"wp:attachment":[{"href":"https:\/\/mic.st\/blog\/wp-json\/wp\/v2\/media?parent=125"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mic.st\/blog\/wp-json\/wp\/v2\/categories?post=125"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mic.st\/blog\/wp-json\/wp\/v2\/tags?post=125"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}