【问题标题】:How to pass data from Button click when the button is placed in UITableViewCell将按钮放置在 UITableViewCell 中时如何从按钮单击传递数据
【发布时间】:2018-08-20 10:52:37
【问题描述】:

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

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

代码:

- (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;

    }
}

【问题讨论】:

  • 你在哪里做 performSegue?
  • 请参阅here 了解一系列解决方案。通常,您不应依赖单元格的内容,而应仅依赖其索引路径,然后您可以将其与数据源一起使用

标签: ios objective-c uitableview segue


【解决方案1】:

您可以在 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 数组的值。

-(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];
}

【讨论】:

  • 获取信息很容易,但现在我想传递数据。你能告诉我传递数据的方法吗
  • 我正在传递数据,例如 //NSString * storyboardName = @"Main"; UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil]; NewViewController * NewView = [storyboard instantiateViewControllerWithIdentifier:@"NewViewControllerID"]; NewView.passedData = @"你的数据"; [self.navigationController pushViewController:NewView 动画:YES];
  • 您需要在destinationViewController.h 中声明一个要导航的变量。比如, // @property(nonatomic,strong) NSString *PassedData;
  • 我做了同样的事情,但更新答案返回值 nil
  • 你在按钮动作中得到按钮标题吗?
【解决方案2】:

实现 TableView 单元委托。

【讨论】:

    猜你喜欢
    • 2013-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2016-12-27
    相关资源
    最近更新 更多