Kasun
Kasun

Reputation: 21

uitable view button action

in my table view i have a button in each cell

UIButton *editButton = [UIButton buttonWithType:UIButtonTypeCustom];
editButton.frame = CGRectMake(281,0, 20, 50);
UIImage *editButtonImage = [UIImage imageNamed:@"edit.png"];
[editButton setImage:editButtonImage forState:UIControlStateNormal];
[editButton setBackgroundColor:[UIColor clearColor]];
[editButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[editButton addTarget:self action:@selector(editButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:editButton];

and button acction is this

-(IBAction)editButtonAction:(id)sender{
     UIButton *btn = (UIButton*) sender;
     UITableViewCell *cell = (UITableViewCell*) btn.superview.superview;
     NSIndexPath *indexPath =[self.table indexPathForCell:cell]; 
     int row = indexPath.row;
     NSLog(@"Selected row is: %d",row);
}

when i click button in table view selected row is always give 0 have any idea? and any code

Upvotes: 1

Views: 148

Answers (4)

Romit M.
Romit M.

Reputation: 898

you create button assign

set button tag as a index of tableView cell.

[editButton setTag:indexPath.row];

in button

-(IBAction)editButtonAction:(id)sender
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:[sender tag] inSection:0]];

    NSLog(@"Selected Cell is: %@",cell);
    NSLog(@"Selected row is: %d",[sender tag]);
}

Upvotes: 0

Lithu T.V
Lithu T.V

Reputation: 20021

Actually the code works fine..Which row you selected for testing?is it 0? Try logging both rows and section.

Also check the outlet of table connected?and if the reference changed anywhere for that outlet

Otherwise the code runs fine for me

    NSLog(@"Row: %d\n ,Section :%d",indexPath.row,indexPath.section);;

Upvotes: 0

piam
piam

Reputation: 653

In this method..

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

add this line:

  button.tag = indexPath.row;

And in this button action ,

 -(IBAction)editButtonAction:(id)sender

add this line:

int row = [sender tag];

Upvotes: 0

janusfidel
janusfidel

Reputation: 8106

alternative solution:

.
.
editButton.tag = indexPath.row;
[editButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[editButton addTarget:self action:@selector(editButtonAction:) forControlEvents:UIControlEventTouchUpInside];
.
.

-(IBAction)editButtonAction:(id)sender{
UIButton *btn = (UIButton*) sender;
NSLog(@"Selected row is: %d",btn.tag);
}

Upvotes: 1

Related Questions