TableView Header Zoom

Want to create a TableView Header Zoom effect like Foursquare, Tapbots, and others?  You can do this in Titanium with only a couple lines of code.

The following code snippet shows how to expand a Ti.UI.ImageView in a Ti.UI.TableView HeaderView to achieve a zoom like effect when the user over scrolls the TableView as demonstrated in the preview below.

TableViewHeader

'use strict';

var win = Ti.UI.createWindow({
    backgroundColor: 'white',
});

//Generate some sample rows
var rows = [];
for (var iLoop=0;iLoop<100;iLoop++){
    rows.push({ title: 'demo row #'+iLoop});
}

//Create our TableView, nothing special
var tableView = Ti.UI.createTableView({
    width:Ti.UI.FILL, height:Ti.UI.FILL,
    data:rows
});

//Create a ImageView for the TableView HeaderView
var imgView = Ti.UI.createImageView({
	width:Ti.UI.FILL, height:150,
	image:"cat.png"
});
//Set our ImageView as the headerView
tableView.headerView = imgView;

win.add(tableView);

//Need to capture a few session variables 
//The most important one is to grab the original height
// of the TableView HeaderView
var _scollTimer = null, 
	_origionHeight = tableView.headerView.height;

//Most of what we need happens in the scroll event
tableView.addEventListener('scroll',function(e){	

	//Clear our timer each time
	if(_scollTimer!==null){
		clearInterval(_scollTimer);
	}

	//If the user has scrolled past the header, 
        //reset the origional height
	if(e.contentOffset.y>_origionHeight){
		if(tableView.headerView.height !== _origionHeight){
			tableView.headerView.height = _origionHeight;
		}		
	}else{
		//Calculate our zoom or expand height
		var zoomOffSet = ((e.contentOffset.y<0)?-1:1);
		var zoomHeight = (tableView.headerView.height + 
					((zoomOffSet*-1)*
                          ((zoomOffSet*e.contentOffset.y)/3)));
		zoomHeight= ((zoomHeight > _origionHeight) 
                            ? zoomHeight : _origionHeight);
		if(tableView.headerView.height !==zoomHeight){
			tableView.headerView.height =zoomHeight;
		}			
	} 

	//Timer is needed since scrollend doesn't always fire
	//so just in case we set a timer to set the origional height
	if(e.contentOffset.y===0){
        _scollTimer = setTimeout(function()
        {
			tableView.headerView.height = _origionHeight;
        },250);		 
	}		
});

//If the user end scrolls something other then the 
//HeaderView check if we need to reset
tableView.addEventListener('scrollend',function(e){	
	if(_scollTimer!=null){
		clearInterval(_scollTimer);
	}	
	if(tableView.headerView.height !== _origionHeight){
		tableView.headerView.height = _origionHeight;
	}	
});

win.open();

Get this snippet on gist here.

Leave a comment