从UITableView中的选定单元格传递数据

时间:2011-12-27 01:35:14

标签: iphone objective-c ios uitableview

我有一个tableview,其中每个单元格都填充了数组中的动态数据。从这里开始,当用户选择一行时,我想将特定数据从该单元格推送到ViewController,以便最终可以用于POST请求。现在我知道我的tableviewcontroller上的代码只会显示数据

- (void)tableView:(UITableView *) tableView didSelectRowAtIndexPath:(NSIndexPath *__strong)indexPath {
    DetailGameController *detail = [self.storyboard instantiateViewControllerWithIdentifier:@"Detail"];
    [self.navigationController pushViewController:detail animated:YES];
    NSUInteger row = [indexPath row];
    detail.rowNum.text = [photoTitles objectAtIndex:row];

}

但我如何实际使用这些数据呢?

这是我所拥有的片段(实际代码有多个NSMutableArrays,但我只包括一个):

     - (void)viewDidLoad
    {

        [super viewDidLoad];
        photoTitles = [[NSMutableArray alloc] init];
 NSURL *url = [NSURL URLWithString:@"http://localhost/test.php"];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setPostValue:dataCenter.data forKey:@"name"];
    [request setDelegate:self];
    [request startAsynchronous];

}
- (void)requestFinished:(ASIFormDataRequest *)request
{

    NSString *responseString = [request responseString];

    NSDictionary *dictionary = [responseString JSONValue]; 
    NSArray *photos = [[dictionary objectForKey:@"photos"] objectForKey:@"photo"];

    for (NSDictionary *photo in photo) {
        NSString *photo = [photo objectForKey:@"photo"];
        [photoTitles addObject:photo];
    }    
}

-(NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
    return [photoTitles count];
}

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


    static NSUInteger const kPhotoTitleTag = 2;
    UILabel *photoTitleLabel = nil;

 static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             SimpleTableIdentifier];
    if(cell == nil){


        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: SimpleTableIdentifier];

        photoTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 25, 170, 14)];
        [cell.contentView addSubview:photoTitleLabel];
}else {
        photoTitleLabel = (UILabel *)[cell.contentView viewWithTag:kPhotoTitleTag];
}
NSUInteger row = [indexPath row];

    photoTitleLabel.text = [photoTitles objectAtIndex:row];
    return cell;

任何帮助我走向正确方向的帮助都会很棒。如果有什么不清楚,请告诉我。

1 个答案:

答案 0 :(得分:6)

为什么要传递行的索引?
传递其他控制器需要使用的信息。

DetailGameController *detail = [self.storyboard instantiateViewControllerWithIdentifier:@"Detail"];
NSUInteger row = [indexPath row];
detail.someProperty = [photoTitles objectAtIndex:row];
detail.someOtherProperty = // other interesting elements ;