Adding multiple lines to your Line Chart using ios-charts

In part 1 we created a single line chart, in this tutorial we'll simply add 2 more data sets to our Line-Chart.

Multiple Lines

To add multiple lines you simply add multiple datasets like so:

    
let dollars1 = [1453.0,2352,5431,1442,5451,6486,1173,5678,9234,1345,9411,2212]
let dollars2 = [5641.0,2234,8763,4453,4548,6236,7321,3458,2139,399,1311,5612]
let dollars3 = [6541.0,3456,7843,5678,5877,7323,7111,6456,5143,4562,6311,10412]
    

Once you have your data sets you can simply repeat what we've did in our last tutorial to add additional lines:

    
func setChartData(months : [String]) {
        
    var yVals1 : [ChartDataEntry] = [ChartDataEntry]()
    for var i = 0; i < months.count; i++ {
        yVals1.append(ChartDataEntry(value: dollars1[i], xIndex: i))
    }
        
    let set1: LineChartDataSet = LineChartDataSet(yVals: yVals1, label: "First Set")
    set1.axisDependency = .Left // Line will correlate with left axis values
    set1.setColor(UIColor.redColor().colorWithAlphaComponent(0.5))
    set1.setCircleColor(UIColor.redColor())
    set1.lineWidth = 2.0
    set1.circleRadius = 6.0
    set1.fillAlpha = 65 / 255.0
    set1.fillColor = UIColor.redColor()
    set1.highlightColor = UIColor.whiteColor()
    set1.drawCircleHoleEnabled = true
        
    var yVals2 : [ChartDataEntry] = [ChartDataEntry]()
    for var i = 0; i < months.count; i++ {
        yVals2.append(ChartDataEntry(value: dollars2[i], xIndex: i))
    }
        
    let set2: LineChartDataSet = LineChartDataSet(yVals: yVals2, label: "Second Set")
    set2.axisDependency = .Left // Line will correlate with left axis values
    set2.setColor(UIColor.greenColor().colorWithAlphaComponent(0.5))
    set2.setCircleColor(UIColor.greenColor())
    set2.lineWidth = 2.0
    set2.circleRadius = 6.0
    set2.fillAlpha = 65 / 255.0
    set2.fillColor = UIColor.greenColor()
    set2.highlightColor = UIColor.whiteColor()
    set2.drawCircleHoleEnabled = true
        
    var yVals3 : [ChartDataEntry] = [ChartDataEntry]()
    for var i = 0; i < months.count; i++ {
        yVals3.append(ChartDataEntry(value: dollars3[i], xIndex: i))
    }
        
    let set3: LineChartDataSet = LineChartDataSet(yVals: yVals3, label: "Second Set")
    set3.axisDependency = .Left // Line will correlate with left axis values
    set3.setColor(UIColor.blueColor().colorWithAlphaComponent(0.5))
    set3.setCircleColor(UIColor.blueColor())
    set3.lineWidth = 2.0
    set3.circleRadius = 6.0
    set3.fillAlpha = 65 / 255.0
    set3.fillColor = UIColor.blueColor()
    set3.highlightColor = UIColor.whiteColor()
    set3.drawCircleHoleEnabled = true
        
    //3 - create an array to store our LineChartDataSets
    var dataSets : [LineChartDataSet] = [LineChartDataSet]()
    dataSets.append(set1)
    dataSets.append(set2)
    dataSets.append(set3)
        
    //4 - pass our months in for our x-axis label value along with our dataSets
    let data: LineChartData = LineChartData(xVals: months, dataSets: dataSets)
    data.setValueTextColor(UIColor.whiteColor())
        
    //5 - finally set our data
    self.lineChartView.data = data
}

Build and run

You should now see multiple lines on your graph, if you're having an issue check out the project files.

In Tags

How to create a Line Chart using ios-charts

This tutorial is part of a series on iso-charts, if you haven't looked over the introduction I'd advise doing so before continuing. In this tutorial we'll be making a single line Line Chart using iOS-charts.

We’ll begin by creating a new single view application, we’ll name it and click create.

Go to the main.storyboard and search for “View” in the Object Library and you’ll see it near the bottom of the list. Drag the view out onto your view controller, position it however you like and add some basic constraints.

In the identity inspector, set your class to “LineChartView”, if you aren’t seeing an option for such a class please make sure you’ve followed the installation steps listed here.

If everything has gone well your main.storyboard should look like this:

20151018043029addLineChartView.png

Setting up our LineChartView object

Click on your Assistant Editor to reveal your ViewController.swift code. We’ll need to add an import statement and adopt a protocol before we can begin wiring up our Line Chart. Modify your class signature to look like this:

    
import Charts
class ViewController: UIViewController, ChartViewDelegate { //...
    

Now we can control drag from our View to our ViewController class and create an outlet named lineChartView with a type of LineChartView.

20151018043325Screenshot 2015-10-17 22.34.21.png
    
@IBOutlet weak var lineChartView: LineChartView!

We can now start setting the properties of our lineChartView object. in your viewDidLoad add the following lines of code:

    
override func viewDidLoad() {
    super.viewDidLoad()    
    // 1
    self.lineChartView.delegate = self
    // 2
    self.lineChartView.descriptionText = "Tap node for details"
    // 3
    self.lineChartView.descriptionTextColor = UIColor.whiteColor()
    self.lineChartView.gridBackgroundColor = UIColor.darkGrayColor()
    // 4
    self.lineChartView.noDataText = "No data provided"
    // 5
    setChartData(months)
        
}

func setChartData() {

}

  1. We set the ChartViewDelegate to our ViewController.
  2. We change the `descriptionText` that will appear at the bottom of our chart.
  3. Here, we set our description text color to white and our grid background color to dark grey.
  4. We make sure our user get feedback if there is not data provided.
  5. Finally, we call / create a custom function that will add data to our chart.

Setting Data

Of course, a very common thing to chart is money over time, and that what we’ll do in this example. So we’ll modify the signature of our setChartData method call to take an array of strings for our months.

    
setChartData(months) // in viewDidLoad
func setChartData(months : [String]) { }
	

And we’ll have to create an array of months as a class level object. While we’re at it, lets go ahead and add three variables that hold our month-to-month dollar amount.

    
let months = ["Jan" , "Feb", "Mar", "Apr", "May", "June", "July", "August", "Sept", "Oct", "Nov", "Dec"]
    
let dollars1 = [1453.0,2352,5431,1442,5451,6486,1173,5678,9234,1345,9411,2212]

For this part of the tutorial, we'll set our chart up with just one set of data, which will create a single red line across our graph. First the code, then the explanation.

    
func setChartData(months : [String]) {
    // 1 - creating an array of data entries
    var yVals1 : [ChartDataEntry] = [ChartDataEntry]()
    for var i = 0; i < months.count; i++ {
        yVals1.append(ChartDataEntry(value: dollars1[i], xIndex: i))
    }
        
    // 2 - create a data set with our array
    let set1: LineChartDataSet = LineChartDataSet(yVals: yVals1, label: "First Set")
    set1.axisDependency = .Left // Line will correlate with left axis values
    set1.setColor(UIColor.redColor().colorWithAlphaComponent(0.5)) // our line's opacity is 50%
    set1.setCircleColor(UIColor.redColor()) // our circle will be dark red
    set1.lineWidth = 2.0 
    set1.circleRadius = 6.0 // the radius of the node circle
    set1.fillAlpha = 65 / 255.0
    set1.fillColor = UIColor.redColor()
    set1.highlightColor = UIColor.whiteColor()
    set1.drawCircleHoleEnabled = true
        
    //3 - create an array to store our LineChartDataSets
    var dataSets : [LineChartDataSet] = [LineChartDataSet]()
    dataSets.append(set1)
        
    //4 - pass our months in for our x-axis label value along with our dataSets
    let data: LineChartData = LineChartData(xVals: months, dataSets: dataSets)
    data.setValueTextColor(UIColor.whiteColor())
        
    //5 - finally set our data
    self.lineChartView.data = data            
}
  1. We start by creating an array of ChartDataEntry items, to which we'll create and append one item for every value stored in our dollars array.
  2. We create a LineChartDataSet that take our array as its first parameter and a label for its second, this dataset represents the line we'll be creating. We continue by setting the attributes that belong to this class object.
  3. Since we're ultimately on a path to create a multi-lined array, we'll create a data set array that will just hold our single set.
  4. Create a data object that takes our months and our single data set.
  5. Set it as our lineCharView objects data 

Build and run

Build and run and you should see your first chart, congratulations, it gets better from here so move on to part II, where we augment this chart with multiple lines.

20151018050325Screen Shot 2015-10-18 at 12.02.56 AM.png

How to create beautiful iOS-charts by example

68747470733a2f2f7261772e6769746875622e636f6d2f64616e69656c67696e64692f696f732d6368617274732f6d61737465722f4173736574732f666561747572655f677261706869632e706e67.png

Welcome to an 8-part series on iOS-charts. ios-charts is a charting library by Daniel Cohen Gindi that was inspired by Philip Jahoda's Android charting library named MPAndroidChart.

In this series I'll introduce you to each of the 8 different types of charts you can make using iso-charts. Before we get started we'll need to install cocoa pods and install the iso-charts library. 

Below are the available and upcoming tutorials, if you'd like to request a tutorial, please do so in the comments below.

If you don't have iOS Charts installed in your application yet, you can follow this quick installation guide video.

 Installation Video Guide

  1. Line Chart
  2. Bar Chart (upcoming)
  3. Bubble Chart (upcoming)
  4. Candle Stick Chart (upcoming)
  5. Combined Chart
  6. Pie Chart
    • Pie Chart (in progress! example files ready)
  7. Radar Chart (upcoming)
  8. Scatter Chart (upcoming)

 

Passing data with the protocol delegate pattern

Delegates are the standard way we pass data between two view controllers. I recently wrote a tutorial on how to pass data by overriding prepareForSegue. In this tutorial I’ll show you how to pass messages back and forth using the “Standard” protocol pattern and without using any segues.

There won’t be an in-depth discussion about protocols or delegates here, for that I defer to Apples Swift Programming Language Guide or one of the many excellent books or online resources that have already covered this topic ad nauseam. 

What I will do, is create a succinct-minimal-working delegate pattern example, using naming conventions that will make it clear how the delegate pattern works. 

Setting Up

We’ll start by creating a single view application.

We’ll add a second View Controller to our storyboard which we’ll need to create a new CocoaTouch file for.  We’ll do that by clicking add new > cocoa touch class >  find UITableViewController… name it PresentedTableViewController and create. 

This controller class will belong to our “presented” view controller, so make sure you add it in your storyboard. Your final storyboard should look like this:

In the first View Controller, lets add a button and a label. We don’t need anything fancy for this exercise, just slap em out there. With split view open, control drag an outlet from your label and name it labelOutlet, and control drag an action from your button and name it doPresent. You should now have something like this:

    
class ViewController: UIViewController {
    
    @IBOutlet weak var textOutlet: UILabel!
    @IBAction func doPresent(sender: AnyObject) {

    }
    
    override func viewDidLoad() {
        super.viewDidLoad()   
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

With an interface that looks like this.

Now, select the other View Controller, the PresentedViewController and add a Text Field and a Button to the View. Just as before, control drag from your Text Field and create an outlet named “textFieldOutlet” and repeat that for your button, this time making an action named “doDismiss”. Your code should look like this:

    
class PresentedViewController: UIViewController {
   
    @IBOutlet weak var textFieldOutlet: UITextField!
    @IBAction func doDismiss(sender: AnyObject) {

    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

And your interface should resemble mine:

Protocol

The Standard pattern is to add our protocol to top of our “presented” class, though I’ve seen people create separate files for these too. We’ll do it the standard way here.

At the top of your PresentedViewController class, just above your class declaration we’ll add the following code.

    
protocol PresentedViewControllerDelegate {
    func acceptData(data: AnyObject!)
}

The convention is to adopt the presented classes name with “Delegate” afterwords. Inside our protocol we’ve defined one function, acceptData that takes AnyObject. I should note that we can define any number of functions and properties inside of our protocol, but no logic. 

Think of a protocol as a binding contract between the protocol and any class that implements it. This contract forces said classes to abide by it's "protocol" and in doing so creates a level of "trust" from the compiler. This "trust" enables us to communicate between two separate bodies of code.

PresentedViewController

We’ll add the required code necessary to receive data from the view controller, but this wont be a one way dialogue. We’ll wire this up so it will send data back to the View Controller as well.

At the class level, add two properties. One being a variable called delegate with a type PresentedViewControllerDellegate. Which will look like this:

    
// create a variable that will recieve / send messages
// between the view controllers.
var delegate : PresentedViewControllerDelegate?
// another data outlet
var data : AnyObject?

We’ll add a print statement in our viewDidLoad that will receive our “data” object from the ViewController. 

    
 override func viewDidLoad() {
    super.viewDidLoad()
    print("\(data!)")

}

Now, we’ll handle our Text Field and Button by adding the following lines of code inside the doDismiss method:

    
@IBAction func doDismiss(sender: AnyObject) {
    if textFieldOutlet.text != "" {
        self.presentingViewController!.dismissViewControllerAnimated(true, completion: nil)
    }
}

You’ll notice that I’ve added a simple check to validate that the text field has content before we call presentingViewController!.disissViewControllerAnimated.

Finally, we’ll add viewWillDisappear which will  send our Text Field data to our delegates acceptData method. 

    
override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    if self.isBeingDismissed() {
        self.delegate?.acceptData(textFieldOutlet.text)
    }
}

Back in our ViewController, we’ll add PresentedViewControllerDelegate to our class signature like this:

    
class ViewController: UIViewController, PresentedViewControllerDelegate {//...

We’ll proceed with our protocol implementation by adding its acceptData(data:AnyObject!) method, which silences the compiler. Inside that method we’ll simply update our text label with the message we entered in PresentedViewController.

    
func acceptData(data: AnyObject!) {
    self.textOutlet.text = "\(data!)"
}

Finally, we’ll address the doPresent action we created earlier. Since in this exercise we aren’t passing values via Segue, we’ll need a method of traversing our data. In this case, it’s by presenting the view controller. We’ll create an instance of our PresentedViewController and with that instance, we can bind to it properties before presenting. That code looks like this:

    
@IBAction func doPresent(sender: AnyObject) {
    let pvc = storyboard?.instantiateViewControllerWithIdentifier("PresentedViewController") as! PresentedViewController
    pvc.data = "important data sent via delegate!"
    pvc.delegate = self
    self.presentViewController(pvc, animated: true, completion: nil)
}

Build And Run

When click the next button you should see the next view controller along with a print line in your console. If you enter some text in the text field and hit your go back button, you’ll see the text you entered assigned to you label.

If you have any troubles, feel free to download the Project Files and browse my code. You can also ask questions in the comments and we’ll get your code running.

Passing values using prepareForSegue

Set Up

The first thing we'll do is create a new single view application. Once the project is loaded, delete your ViewController.swift from your Project Manager as well as from your Storyboard.

Once you have this find a Navigation Controller in your object library and drag it out onto your storyboard, select your Navigation Controller in your StoryBoard and choose "Is Initial View Controller" in your Attributes Inspector. Now that you've got your initial view controller set up let's add a new Cocoa class to your project by right-clicking your main project folder in Project Manager and selecting "New File...". Select, iOS > Source > Cocoa Touch Class and then select next. Create a UITableViewController like I've done here.

We'll assign this new class as our table view in our storyboard by selecting our table view and adding our newly created class in our Identity Inspector it'll look like this.

Before we move on, click on your prototype cell in your storyboard and give it an Identifier of "Cell" and give it a Style of Basic for this example.

Now that we have our main controller lets add a View Controller that we'll send our values to. Drag a View Controller our onto your storyboard just as we did for our Navigation Controller. And just as we did with our FirstTableViewController, we'll add another Cocoa Touch Class, this time uses a UIViewController and we'll name it SecondViewController. Remember to add your new class to your View Controller in your storyboard as we did before for our FirstViewController.

Finally, we'll create a segue by control dragging from our FirstTableViewController to our SecondViewController like so.

Click on your new segue and in your Attributes Inspector add an Identifier, I chose "SendDataSegue" for this example.

We'll also want to add a label to our new View Controller, place it dead center and give it some simple constraints. Finally, create an outlet in your SecondViewController.swift by control dragging from your outlet to your class. 

Name your outlet viaSegueLabel, it should look like this:

@IBOutlet weak var viaSegueLabel: UILabel!

Code

Open your SecondViewController and at the class level, add a property called viaSegue like this:

var viaSegue = ""

Then inside your view controller we'll assign the value of viaSegue to our viaSegueLabel, add the following code to your viewDidLoad:

override func viewDidLoad() {
        super.viewDidLoad()

        viaSegueLabel.text = viaSegue
        // Do any additional setup after loading the view.
    }

We're finished with our viewController, lets move on to our tableViewController.

In our FirstTableViewController lets first quickly set our numberOfSectionsInTableView to 1 and numberOfRowsInSection to 10, I won't go into any detail here:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 10
    }

Now, let's add a method called prepareForSegue, which does exactly what it sounds like it does, it prepares for the upcoming segues.  To learn more about prepareForSegue see Apples Developer Guide. Here's the implementation:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "SendDataSegue" {
            if let destination = segue.destinationViewController as? SecondViewController {
                
                let path = tableView.indexPathForSelectedRow
                let cell = tableView.cellForRowAtIndexPath(path!)
                destination.viaSegue = (cell?.textLabel?.text!)! 
            }
        }
    }

In this method, we're determining which segue we're preparing for with segue.identifier, we're then using an if let to safely attempt to assign a segue with a destinationViewController with a type of ours. Getting the type lets us model the properties within, thus giving us access to our viaSegue in our SecondViewController, which we take advantage of here.

We haven't actually set up a segue yet, we'll do that now. Lets add a new tableView override function for didSelectRowAtIndexPath, this will allow us to trigger a segue from whichever row we select. The implementation is simple so I'll stop rambling.

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        _ = tableView.indexPathForSelectedRow!
        if let _ = tableView.cellForRowAtIndexPath(indexPath) {
            self.performSegueWithIdentifier("SendDataSegue", sender: self)
        }
        
    }

It's important to note that we are using our segue by it's identifier "SendDataSegue".

Last but not least, lets make sure our cells have some data to pass. Since we used the Basic setup for our prototype cell earlier, we've got access to a textLabel by default, so lets use it:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
        
        // Configure the cell...
        cell.textLabel?.text = "Hello from cell #\(indexPath.row))"
        
        return cell
    }

Build and Run

If everything as gone according to my master plan, you should've passed the value you selected. If you're having problems drop a line below or check out the project files.

Installing CocoaPods

What is CocoaPods?

"CocoaPods manages library dependencies for your Xcode projects.

The dependencies for your projects are specified in a single text file called a Podfile. CocoaPods will resolve dependencies between libraries, fetch the resulting source code, then link it together in an Xcode workspace to build your project.

Ultimately the goal is to improve discoverability of, and engagement in, third party open-source libraries by creating a more centralised ecosystem."

source

Installing cocoa pods

In terminal use the following two commands:

sudo gem install cocoapods
pod setup

If you're using El Capitan and experiencing issues try this:

sudo gem install -n /usr/local/bin cocoapods
pod setup
In Tags

How to add dynamic meta tags to your asp.net mvc views

Setting Up

We'll start by creating a new ASP.NET MVC 5 project and we'll make sure we have individual accounts selected. We're doing this so that we get entity framework and our dbcontext out-of-the-box. 

94f32fe3-cd15-473a-8872-884f09f545f1newProjectIndividualAccountsSelected.PNG

In your new project, let's create two models. We'll make a Page model and a MetaViewModel. The Page model will contain all of the properties that we'll be using in our database, the MetaViewModel will be used to shape the data for rendering our partial view. This will make perfect sense when you see it in context.

Adding Models

So let's create our Page.cs file in our model's folder and then we'll add the following code:

 
    
public class Page
{
    public int Id { get; set; }
    public string Author { get; set; }
    public string Keywords { get; set; }
    public string Description { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
}

and we'll go ahead an add our MetaViewModel as well in the same manor, here's the code:

    
public class MetaViewModel
{
    public string Author { get; set; }
    public string Keywords { get; set; }
    public string Description { get; set; }
}

Let's continue by adding our Page class to our dbcontext by creating a new property for it in our IdentityModels file (in your model folder). We're just going to add one line, like so:

    
public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext() 
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    public DbSet Pages { get; set; } // this is the line we're adding
}

Build your project but don't actually run it yet.

Controller Logic

Now that we've built our project the compiler knows about our new models for sure. Let's add a controller by right-clicking on the controller folder and selecting add > controller.

We'll choose to create an "MVC 5 Controller with views using Entity Framework", you'll see a form appear add the following constraints: 

071552d9-9f98-4712-a71a-45d9c1f73879createPagesController.PNG

We'll put our MetaViewModel to use in our new PagesController, add the following Action Result to your controller.

    
public ActionResult ListMeta(int? id = 1)
{
    var post = db.Pages.Find(id);

    MetaViewModel meta = new MetaViewModel();
    meta.Author = post.Author;
    meta.Keywords = post.Keywords;
    meta.Description = post.Description;

    return PartialView("~/Views/Pages/_ListMeta.cshtml", meta);
}

We'll need a Partial View

Notice that we're returning a partial view in this method, obviously that doesn't exist yet, so we'll need to make that now. Right click on your "ListMeta" method and select Add View. A dialog window will appear, make sure you fill it out just as I've done below.

76ed1ee5-5eba-4af3-8e87-8812e8afdbf4metaform_partial.png

Once your new partial view is created lets replace the code with the following:

    
@MetatagsExample.Models.MetaViewModel

< meta name="description" content="@Html.DisplayFor(modelItem => Model.Description)">
< meta name="keywords" content="@Html.DisplayFor(modelItem => Model.Description)">
< meta name="author" content="@Html.DisplayFor(modelItem => Model.Author)">

Lets open up our Details page for this controller by going to Views > Pages > Details.cshtml, we'll add the following lines to the top of our class (just below our @model code): 

 
    
@section metatags {
    @Html.Action("ListMeta", "Pages", new { id = Model.Id })
}

Now, lets open our _Layout.cshtml, which acts as a template for all of our future Pages and we'll add the following line inside our <head> tags:

    
@RenderSection("metatags", false)

Alright, we're ready to create our database!

Open your package manager console window by selecting view > other windows > package manager console. Once your console has opened we're going to run the following three commands individually.

  • enable-migrations
  • add-migration initial
  • update-database

If everything was successful, you now have a local database which will serve nicely for our example.

Build and Run

Finally, lets build and run our project. Once your project compiles and the browser opens. Navigate to the following URL:

localhost:{port}/pages/create

You'll see a create form, fill it out and click create. You've just created a "Page" that contains your specified meta data. After your record posts, you'll see a new screen with the results. Click the "details" link and you'll be taken to the details page.

Right-click and choose "View Source" and you should see your specified source as I've shown below

c59d96ea-e78a-4eef-8e25-f16ebd5228f2pagesource.png

That's it... If you have any problems just leave a comment and I'll try to clarify for you.