繁体   English   中英

在iOS中单击UITableViewCell后,如何获取字典中的键值?

[英]How to get value of key in dictionary after UITableViewCell is clicked in iOS?

我试图在UIViewController内设置UITableView 这对我来说可以。

首先,我做了什么:

1)我从服务器收到这样的响应:

[{"email_id":"adas@faga.gs","id":66,"mobile_no":"1236547895","name":"asad","relation":"dsfs"},{"email_id":"raj@ghj.com","id":67,"mobile_no":"5632145412","name":"raj","relation":"xyz"},{"email_id":"surajsukale@gmail.com","id":68,"mobile_no":"8698819943","name":"suraj","relation":"self"}]

2)在原型单元中的所有字典中成功显示4个值。

即: email_idmobile_nonamerelation

注意:这里我得到5个参数作为响应,但是我只显示4个。

这是我为此所做的:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [menuItems count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"EmergencyContactCell";

    EmergencyContactCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    NSDictionary *content = [menuItems objectAtIndex:indexPath.row];

    cell.name.text = content[@"name"];
    cell.email.text = content[@"email_id"];
    cell.mobile.text =content[@"mobile_no"];
    cell.relation.text =content[@"relation"];

    return cell;
}

对我来说非常适合

现在,我想要什么?

当我单击任何单元格时,我想获取该词典中的特定ID。 我应该在这里做什么:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld",(long)indexPath.row);

// What should i do here is my question ??
    }

请任何人都可以解决我的问题。 帮助将是可观的。

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
   NSDictionary *content = [menuItems objectAtIndex:indexPath.row];
    NSString *id = content[@"id"];
 }

但是我不明白为什么尽管您解析了cellForRowAtIndexPath的值,但仍然要求在didSelectRowAtIndexPath进行相同的处理?

将以下代码写入您的didSelectRowAtIndexPath方法:

NSDictionary *content = [menuItems objectAtIndex:indexPath.row];
NSString *id = content[@"id"];

您尚未在列表中显示id ,但可以访问它。 因为它在您的字典中。

我认为您正在寻找类似的东西

NSDictionary *content = [menuItems objectAtIndex:indexPath.row];
NSNumber *number = content["id"];

如果您需要纯数据类型,请使用适当的属性,例如:

int iNumber = number.intValue;

请使用这个

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
       int id = [[[menuItems objectAtIndex:indexPath.row]valueForKey:@"id"]intValue];
    }

您可以通过以下方式访问menuItems:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *yourItem = [menuItems objectAtIndex:indexPath.row];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM