Skip to content

Instantly share code, notes, and snippets.

@aaronksaunders
Created October 16, 2011 07:54
Show Gist options
  • Save aaronksaunders/1290632 to your computer and use it in GitHub Desktop.
Save aaronksaunders/1290632 to your computer and use it in GitHub Desktop.
More Fun with TableView Rows
var win = Ti.UI.createWindow({});
var tableView = Ti.UI.createTableView({});
for(var i = 0; i < 5; i++) {
var checkBox = Ti.UI.createView({
width : 20,
height : 20,
done : false,
item_type : "CHECKBOX", // us this to know we clicked a checkbox
id : "CHECKBOX_" + i,
left : 5,
borderWidth : 10,
borderRadius : 10
});
checkBox.borderColor = 'red';
var label = Ti.UI.createLabel({
width : 250,
height : 35,
item_type : "LABEL", // us this to know we clicked a checkbox
id : "LABEL_" + i,
text : "LABEL_" + i,
left : 35,
});
var tableRow = Ti.UI.createTableViewRow();
// set this so we dont get the blue highlight when selecting the button
tableRow.selectedBackgroundColor = 'transparent';
tableRow.add(checkBox);
tableRow.add(label);
// add this helper method to find if row is green
// could do this other ways, but this is what I
// chose for the example
tableRow.isGreen = function() {
return this.children[0].done
}
tableView.appendRow(tableRow);
}
// put an event listener on the whole row, but look for the checkbox when
// handling the specific event
tableView.addEventListener('click', function(evt) {
// if the item clicked was a check box, then handle it
if(evt.source.item_type === "CHECKBOX") {
// just for fun, lets find the label on this row
Ti.API.debug(JSON.stringify(findElement(evt.source.parent, "LABEL_" + evt.index)));
if(evt.source.done === true) {
evt.source.done = false;
evt.source.borderColor = 'red';
} else {
evt.source.done = true;
evt.source.borderColor = 'green';
}
Ti.API.debug("Selected Rows " + checkedRowsAre());
} else {
alert("Clicked the row, but not the checkbox");
}
});
win.add(tableView);
win.open();
/**
* helper to find an element, can be used when there are
* multiple elements in a row and you need to find one
*
* @param _o {Object} parent object to find elements in
* @param _i {String} id of the element you are looking for
*/
function findElement(_o, _i) {
for(var x in _o.children) {
if(_o.children[x].id === _i) {
return _o.children[x];
}
}
return "";
}
/**
* simple method to get the list of items selected
*/
function checkedRowsAre() {
// get the rows; there is a default section in all tables so that
// is why we need to get the rows this way
var selected = [];
var rows = tableView.data[0].rows;
// iterate through the rows to find out which ones are selected,
// add the index to an array
for(var x in rows) {
if(rows[x].isGreen() === true) {
selected.push(x);
}
}
// flatten the array to a comma delimited string of row indexes
if(selected.length) {
return selected.join(",");
} else {
return "";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment