john
john

Reputation: 1319

iPhone UITableView, how to set default row as checked onViewLoad?

I have a UITableView correctly populating with data. The table view is inside another view. When this parent view is loaded, how can I set the first row in the table view to have a checkmark?

@implementation PrefViewController 

@synthesize label, button, listData, lastIndexPath;

-(void) viewDidLoad {
    NSArray *array = [[NSArray alloc] initWithObjects:@"European",@"Spanish", nil];
    self.listData = array;

    // SET TABLEVIEW ROW 0 to CHECKED
    [array release];
    [super viewDidLoad];
}

Edit: I only want the first row to be check when the view is created. Only one row in the second group should be able to be selected (have a checkmark). This is my full cellForRowAtIndexPath, can you spot the problems?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CheckMarkCellIdentifier = @"CheckMarkCellIdentifier";  
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CheckMarkCellIdentifier];

NSUInteger row = [indexPath row];
NSUInteger oldRow = [lastIndexPath row];

if(indexPath.section == 1)
{
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CheckMarkCellIdentifier] autorelease];
        if (indexPath.row == 0)
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }

    cell.text = [listData objectAtIndex:row];
    cell.accessoryType = (row == oldRow && lastIndexPath != nil) ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;
}
else
{
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CheckMarkCellIdentifier] autorelease];
    }

    cell.text = [aboutData objectAtIndex:row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

return cell;
}

Upvotes: 0

Views: 3144

Answers (2)

Rupnarayan Basena
Rupnarayan Basena

Reputation:

Try this answer:

if (cell.accessoryType == UITableViewCellAccessoryNone) {
   cell.accessoryType = UITableViewCellAccessoryCheckmark;  
}
else if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
   cell.accessoryType = UITableViewCellAccessoryNone;
}

Upvotes: 0

Brandon Schlenker
Brandon Schlenker

Reputation: 5088

You would need to implement this in your Table View Controllers cellForRowAtIndexPath method.

if (indexPath.row == 0)
cell.accessoryType = UITableViewCellAccessoryCheckmark;

Upvotes: 4

Related Questions