0

我已经到处搜索了教程或可以向我展示如何从填充单元格 cell.textlabel.text 字段的数组中传递数据的东西,该字段在该节点中也有其他信息......

为简单起见,我正在从生成 XML 文件的 Web 服务中获取我正在解析的数据。它返回一个“ID”、“Name”、“OtherID”字段。然后用解析的 XML 填充 UITableViewController,基本上只是 cell.textLabel.text 的“名称”字段。我有所有这些工作。

但是,我现在需要做的是:

当用户确实选择了一行时,我需要将“ID”和“OtherID”字段(未显示在单元格中)设置为变量,切换视图,并使用旧视图中的变量设置新视图的 UILabel。

这就是我不知所措的地方......

有人可以向我指出如何完成此代码的教程或代码示例的方向吗?或者,如果您有类似的事情与我分享?

非常感谢您的参与!

4

1 回答 1

1

当您在 中设置 UITableViewCell 时tableView:cellForRowAtIndexPath:,您正在使用来自结果数组中某个索引的数据,基于单元格的索引路径。

执行您要求的最简单方法是使用所选单元格的索引路径并执行与上述相同的计算以找到该特定索引。然后你可以从原始数组中获取你需要的一切。看起来像这样:

- (NSUInteger)arrayIndexFromIndexPath:(NSIndexPath *)path {
    // You could inline this, if you like.
    return path.row;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)path {
    NSUInteger index = [self arrayIndexFromIndexPath:path];
    NSDictionary *data = [self.dataArray objectAtIndex:index];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:...];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:... reuseIdentifier:...] autorelease];
    }

    // ... Set up cell ...

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)path {
    NSUInteger index = [self arrayIndexFromIndexPath:path];
    NSDictionary *data = [self.dataArray objectAtIndex:index];

    // ... Do whatever you need with the data ...
}

一个稍微复杂(但可能更健壮)的方法是继承 UITableViewCell 以添加属性或 ivars 来保存您需要的数据;这可以像单个属性一样简单,以保存原始数组中的整个值。然后在选择方法中,您可以从单元格本身获取所需的所有内容。看起来像这样:

MyTableViewCell.h:

@interface MyTableViewCell : UITableViewCell {
    NSDictionary *data_;
}

@property (nonatomic, retain) NSDictionary *data;

@end

MyTableViewCell.m:

@implementation MyTableViewCell

@synthesize data=data_;

- (void)dealloc {
    [data_ release]; data_ = nil;
    [super dealloc];
}

@end

接着:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)path {
    NSUInteger index = [self arrayIndexFromIndexPath:path];
    NSDictionary *data = [self.dataArray objectAtIndex:index];

    // Remember, of course, to use a different reuseIdentifier for each different kind of cell.
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:...];
    if (!cell) {
        cell = [[[MyTableViewCell alloc] initWithStyle:... reuseIdentifier:...] autorelease];
    }

    cell.data = data;

    // ... Set up cell ...

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)path {
    MyTableViewCell *cell = [tableView cellForRowAtIndexPath:path];
    NSDictionary *data = cell.data;

    // ... Do whatever you need with the data ...
}
于 2011-04-12T16:26:55.923 回答