将按钮放在UITableViewCell中时如何从按钮单击传递数据

时间:2018-08-20 10:52:38

标签: ios objective-c uitableview segue

我有一个表格视图,其中每一行都有一个按钮。正在存储数据作为按钮的标题。

我需要的:我想将所选按钮的标题传递给目标视图控制器。

代码

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

    NSDictionary *dict = _json[indexPath.row]

    [cell.bRedeem setTitle:dict[@"n_id"] forState:UIControlStateNormal];

}

- (IBAction)redeemClicked:(UIButton *)sender {

    UIButton *button = (UIButton *)sender;

    _nID = button.currentTitle;


}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

    if ([segue.identifier isEqualToString:@"showOffers"]) {

        offerList *details = (offerList *)segue.destinationViewController;

        details.nearID = _nID;

    }
}

2 个答案:

答案 0 :(得分:0)

您可以在cellForRowAtIndexPath方法中添加一个Button目标。

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

    [cell.btnOne addTarget:self action:@selector(ButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [cell.btnOne setTag:indexPath.row];

}

在按钮操作中,您可以使用[sender tag]值获取Json Array的值。

-(IBAction)ButtonClicked:(id)sender
{
    NSDictionary *dict = [JsonArray objectAtIndex:[sender tag]];
    NSLog(@"Selected Dictionary : %@",dict);
    NSString * storyboardName = @"Main"; UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil]; 
    NewViewController * NewView = [storyboard instantiateViewControllerWithIdentifier:@"NewViewControllerID"]; 
    NewView.NearId = [dict valueForKey@"n_id"]; 
   [self.navigationController pushViewController:NewView animated:YES];
}

答案 1 :(得分:0)

实现TableView单元格委托。