如何从iOS中的表视图中选择一行?

时间:2015-12-12 06:00:51

标签: ios json uitableview

我有本地JSON并在第一页显示。

之后我想从tableview中选择一行。当我选择行时,它将显示来自url的其他JSON,不同的行具有不同的json。但是,我不知道如何找出一行。我尝试了很多方法,但它不起作用。

以下是第一页的代码:

@implementation HKTableViewController{
    NSArray *_location_array,*_hki;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    JSONLoader *location_jsonLoader = [[JSONLoader alloc] init];
     NSURL *url = [[NSBundle mainBundle] URLForResource:@"locations" withExtension:@"json"];

    //NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/funhiking/index.php/index/getHKIsland"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        _location_array = [location_jsonLoader locationsFromJSONFile:url];

        [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
    });
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    DistrictTableViewController *district = segue.destinationViewController;

    NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];

    district.location = [_location_array objectAtIndex:indexPath.row];

    if (indexPath.row == 0) {
        // Create a new JSONLoader with a local file URL
        JSONLoader *jsonLoader = [[JSONLoader alloc] init];

        //go to web to take json file
        NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/funhiking/index.php/index/getHKIsland"];

        // Load the data on a background queue...
        // As we are using a local file it's not really necessary, but if we were connecting to an online URL then we'd need it
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            _hki = [jsonLoader hkiFromJSONFile:url];
            // Now that we have the data, reload the table data on the main UI thread
            [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
              });
    }
}

#pragma mark - Table View Controller Methods

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HKCell"];

    Locations *location = [_location_array objectAtIndex:indexPath.row];

    cell.textLabel.text = location.title;
    NSLog(@"%@", location.title);

    return cell;
}

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

1 个答案:

答案 0 :(得分:0)

您可以在设置表视图的委托后使用表视图的didselectrowatindex委托方法,然后您可以在此方法中从您的数组中获取对象,并且可以简单地显示JSON URL。 快乐的编码...