Skip to main content

UITableView…the correct way



I'm trying to make a UITableView like the native calendar app:





enter image description here





but I'm trying to learn the best way to do this. I'm able to get this for the most part with a switch statement in the cellForRowAtIndexPath method, but I'm having troubles changing the textColor when a cell is selected.





For some reason cell.isSelected is always NO, and I have no way to reload the tableview after another cell is selected anyway.





Should I subclass UITableViewCell for something this simple and store an array of cells?





Any help would be appreciated, thanks.


Comments

  1. There is no need to subclass, as stated in the app doc the delegation function:

    tableView:willSelectRowAtIndexPath:


    should do the trick

    EDIT:

    Below you find some code that should demonstrate the idea of using the delegate. Please note that this code is untested, as i am currently not in front of my xcode.

    -(void)willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (prevIndexPath != nil) {
    UITableViewCell* prevCell = [self.tableView cellForRowAtIndexPath: prevIndexPath];
    prevCell.textLabel.textColor = [UIColor black]; // your initial color here
    }

    UITableViewCell* cell = [self.tableView cellForRowAtIndexPath: indexPath];
    cell.textLabel.textColor = [UIColor green];

    prevIndexPath = indexPath;
    }


    Make sure to set the UITableViewDelegate protocol to your controlling class that manages your TableView and set the tableViews.delegate to that.

    To make this code run, you also have to define a property or variable with the name prevIndexPath. This ones holds the previously selected cell that is needed to revert to the cell to its initial color.

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...