开发者

identifying Button selection of each row in Tableview?

开发者 https://www.devze.com 2022-12-13 14:34 出处:网络
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  • (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(230.0f, 4.0f, 60.0f, 36.0f);
    [btn setTit开发者_JAVA百科le:@"OK" forState:UIControlStateNormal];
    [btn setTitle:@"OK" forState:UIControlStateSelected];
    [btn addTarget:self action:@selector(onClickRename:) forControlEvents:UIControlEventTouchUpInside];
    [cell addSubview:btn];
    
    return cell;
    

    }

but if the user selects the button on particular row, i can change that image through onClickRename...but can i get inwhich row's image has been touched through

  • (void)tableView:(UITableView )tableView didSelectRowAtIndexPath:(NSIndexPath)indexPath ?


you could do something like

[btn setTag:[indexPath] row]

in your cell setup, and then

- (void) onClickRename:(id)sender {
    int row = sender.tag;
} 

you'd know which table row was hit.


Apple uses the following technique in their Accessory sample code:

- (void)checkButtonTapped:(id)sender event:(id)event
{
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
    if (indexPath != nil)
    {
        // do what you want with the item at indexPath
    }
}


In Swift, you can set a tag for each button

Also, set each index value as its tag, we get to know which button is clicked at which row.

to set tag, in cellForAtIndexPath

cell.button.tag = indexPath.row


in button Action

@IBAction func anAction(_sender : AnyObject){

 let tappedButton = sender.tag // gives the row and button

}
0

精彩评论

暂无评论...
验证码 换一张
取 消