Martin Ottenwaelter

  1. Alternate row colors in SC.ListViews

    This post will show you how to create a SproutCore ListView with alternate row colors.

    Let’s add alternate row colors to the Todos tutorial’s list view. Clone the source code, then switch to the step-5 branch. It should look like this:

    Todos, Step 5

    The code that’s actually responsible for the ListView is in main_page.js:46:

    middleView: SC.ScrollView.design({
      hasHorizontalScroller: NO,
      layout: { top: 36, bottom: 32, left: 0, right: 0 },
      backgroundColor: 'white',
      contentView: SC.ListView.design({
        contentBinding: 'Todos.tasksController.arrangedObjects',
        selectionBinding: 'Todos.tasksController.selection',
        contentValueKey: "description",
        contentCheckboxKey: "isDone",
        canEditContent: YES,
        canReorderContent: YES,
        canDeleteContent: YES,
        destroyOnRemoval: YES,
        rowHeight: 21
      })
    }),
    

    This creates a standard list view whose rows are instances of the SC.ListItemView class. We want to customize the appearance of these rows, so we are going to subclass the SC.ListItemView class and override the render method:

    Todos.ListItemView = SC.ListItemView.extend({
      render: function(context, firstTime) {
        if (this.get('contentIndex') % 2 === 0) {
          context.addClass('even');
        } else {
          context.addClass('odd');
        }
        return sc_super();
      }
    });
    

    Let go through this code snippet step by step:

    Now, we need to tell the contentView that it should use the Todos.ListItemView class for rows. This is done by adding the following line to the contentView’s parameters:

    exampleView: Todos.ListItemView,
    

    Finally, we need to add some css code to style the odd and even rows. Create a list_item.css file in your english.lproj folder:

    .sc-list-item-view.even {
      background-color: #E4E4E4;
    }
    

    Reload your browser, it should look like that:

    Todos, with alternate row colors

    EDIT: As nexneo points out, there is a simpler way to get the current row index. I’ve replaced this.owner.contentIndexForLayerId(this.layerId) by this.get('contentIndex'). Thanks!

  2. blog comments powered by Disqus