开发者

Table View - On Click If Statement

开发者 https://www.devze.com 2023-03-22 05:29 出处:网络
All, I have a table view that I need to react differently when a cell is clicked with string X in it vs string Y. X would take you to to X View (XViewController) and Y would take you to Y View (YView

All,

I have a table view that I need to react differently when a cell is clicked with string X in it vs string Y. X would take you to to X View (XViewController) and Y would take you to Y View (YViewController), etc etc. Where would be the best place to insert this if statement, and how would I make it 开发者_如何学Gotransition to the correct view?

Thanks


You want to implement

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

Then you can access the cell in question to read the string and present the appropriate view controller.

For example:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    if ([cell.text isEqualToString:stringX]) {
        XViewController *xvc = [[XViewController alloc] init];
        [self presentModalViewController:xvc animated:YES];
        [xvc release];
    } else {
        YViewController *yvc = [[YViewController alloc] init];
        [self presentModalViewController:yvc animated:YES];
        [yvc release];
}

Then, in whichever viewController is pushed, you can dismiss it with

[self dismissModalViewControllerAnimated:YES];


The method:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;

Is what where you would do this. You would then grab the cell from that index path:

UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];

Finally, check the string. The code should look like this:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;{
  UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];

  if([cell.text isEqualToString:X]){
    // load view X and push onto the view controller
  }
  else{
    // load view Y and push onto the view controller
  }
}

If you used Custom cells, just look at the custom property instead of .text.

You should really look here:

Apple Navigation Controller Reference

It's really simple. Just alloc the new view controller, and push it onto the navigation controller:

NewViewController * newView = [[NewViewController alloc] init];
[self.navigationController pushViewController:newView animated:YES];
[newView release];
0

精彩评论

暂无评论...
验证码 换一张
取 消