Clicking Event in UITableView

Christien picture Christien · Sep 26, 2012 · Viewed 41.5k times · Source

I have a button and Table. Now I want to click in such way that Whenever I select any row in tableview and press the button, that particular button press event would happen. For that, firstly I have give tag to each row i.e

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *LabelCellIdentifier = @"cell";
UITableViewCell *cell;
cell = [tableView dequeueReusableCellWithIdentifier:LabelCellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:LabelCellIdentifier];


}

if (indexPath.row <= [_arrayMp3Link count]) {

    cell.textLabel.text = [_arrayMp3Link objectAtIndex:indexPath.row];

     }

// now tag each row
NSInteger count = 1;
for (NSInteger i = 0; i < indexPath.section; i++) {
    count += [[tableView dataSource] tableView:tableView numberOfRowsInSection:i];
}
count += indexPath.row;
// dequeue, create and configure...
cell.tag = count;



return cell;
}

and now in putting event in button when I select the row and press my button. But not getting the correct things.

(IBAction)doDownload:(id)sender {
// to select first row
if(cell.tag==1)
{
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"http://www.google.com"]]; 
}

Answer

TheTiger picture TheTiger · Sep 26, 2012

Declare an int variable globally -

int rowNo;

Then assign value to it in didSelectRowAtIndexPath: method

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 {
     rowNo = indexPath.row;
 }

Now you have the indexNo. of selected row.

-(IBAction)doDownload:(id)sender
{
    //Now compare this variable with 0 because first row index is 0.
    if(rowNo == 0)
    {
         [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"http://www.google.com"]];
    }
}