Search code examples
titanium

Custom Table Header View in Titanium


I want to create a custom table header View, but I want that view to be repeated I have 3 sections and in all 3 sections I want to view the same header View for the table.

Here is my code :

 var section1HeaderView = Ti.UI.createView({ height: 40,backgroundColor:'#00928F' });
var section1HeaderLabel = Ti.UI.createLabel({ text: 'I am the header, hear me roar!',color:'black' });
section1HeaderView.add(section1HeaderLabel);

var sectionFruit = Ti.UI.createTableViewSection({ headerView: section1HeaderView });
sectionFruit.add(Ti.UI.createTableViewRow({ title: 'Apples' }));
sectionFruit.add(Ti.UI.createTableViewRow({ title: 'Bananas' }));

var sectionVeg = Ti.UI.createTableViewSection({ headerTitle: 'Vegetables' });
sectionVeg.add(Ti.UI.createTableViewRow({ title: 'Carrots' }));
sectionVeg.add(Ti.UI.createTableViewRow({ title: 'Potatoes' }));

var table = Ti.UI.createTableView({
  data: [sectionFruit, sectionFruit,sectionFruit]
});

$.win.add(table);

Output: enter image description here

If you notice it is taking the height property but not the background color property nor the label added?


Solution

  • This doesn't answer the "Why can't I use the same headerView for multiple sections" (probably some restriction in Titanium or on native?) question but it does solve your problem.

    var headerViewArray = [];
    for(var i =0; i<3;i++){
        var headerView = Ti.UI.createView({ height: 40,backgroundColor:'#00928F' });
        var headerLabel = Ti.UI.createLabel({ text: 'I am the header, hear me roar!',color:'black' });
        headerView.add(headerLabel);    
        headerViewArray.push(headerView);
    }
    
    var fruitData = [{'title':'Apples'},{'title':'Bananas'}];
    var vegData = [{'title':'Carrots'},{'title':'Potatoes'}];
    var meatData = [{'title':'Chicken'},{'title':'Beef'}];
    
    var sectionFruit = Ti.UI.createTableViewSection({ headerView: headerViewArray[0] });
    _.each(fruitData, function(item){
        sectionFruit.add(Ti.UI.createTableViewRow(item));
    })
    
    var sectionVeg = Ti.UI.createTableViewSection({ headerView: headerViewArray[1] });
    _.each(vegData, function(item){
        sectionVeg.add(Ti.UI.createTableViewRow(item));
    })
    
    var sectionMeat = Ti.UI.createTableViewSection({ headerView: headerViewArray[2] });
    _.each(meatData, function(item){
        sectionMeat.add(Ti.UI.createTableViewRow(item));
    })
    
    var table = Ti.UI.createTableView({
      data: [sectionFruit, sectionVeg, sectionMeat]
    });
    
    $.index.add(table);
    $.index.open();