简体   繁体   中英

UITableView - get data when tapped

My question is that is it possible to get text data and read it in my ViewController from php when the cell is tapped?

I'm guessing didSelectRowAtIndexPath is the key to do this, but I'm not sure how to write.

I am able to get data from php into my TableViewController as below;

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

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

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    NSDictionary *info = [json objectAtIndex:indexPath.row];
    cell.textLabel.text = [info objectForKey:@"Artist"];
    cell.detailTextLabel.text = [info objectForKey:@"Song"];


    return  cell;
}

Your code is I think wrong. Check if there any data in json by checking

NSLog(@"%@ and %@",[info objectForKey:@"Artist"],  [info objectForKey:@"Song"]);

and tell me if any result comes out. if not then there is some mistake in your php else your data should show there.

The code you have written kind of contradicts what you explained in the beginning. However, This is how it should be done:

First off you will need to get the data you want to display. You can get this from an external website (php, as you call it), plist, xml or whatever you want. You can do this when you have your tableview initiated (eg using ASIHTTPRequest ) or before you initiate your tableview and just send it in using a custom init method. Second, you need to read the contents you have recieved. Usually it great to get is in a NSArray format. This depends on your implementation of the data source you are fetching data from.

If you are new to objective-c and cocoa-touch, you should start off with some quick tutorials regarding UITableView. I have written one myself, but currently I guess its (very) outdated. You could still have a look at it though: http://paulpeelen.com/2009/08/14/developing-with-iphone-3-0-x-simple-uitableview/

use this method of code.

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{ 
  //retrive your data here.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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