简体   繁体   中英

how to get selected row IOS

如何知道当前在表视图中选择了哪一行,而不使用任何全局变量来使用此方法存储最后单击的行。

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

If you have the UITableView in an outlet property, you can get the selected row like this:

[tableView indexPathForSelectedRow]

which will return an indexPath containing row and section numbers of the selected row.

See http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableView_Class/Reference/Reference.html#//apple_ref/occ/instm/UITableView/indexPathForSelectedRow .

You don't need a global variable. if you need to track the currently selected row, you can create a member variable (iVar) in the class that is the delegate for the table view callbacks.

That method passes you the indexPath which has the row that was selected. If you want remember that for other function callbacks, then create a property or iVar in that class.

In header:

@interface MyTableViewController : UITableViewController {
    NSInteger _selectedRow;
}

In implementation

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
   _selectedRow = indexPath.row;
}

Edit: Store in NSUserDefault

In this delegate method u can get Currently Selected Row Add int curRowIndex in .h file

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
  curRowIndex = indexPath.row
  NSLog(@"Currently Selected Row: %d",curRowIndex);
}

I have done this way ....

NSIndexPath *selectedIndexPath = [table indexPathForSelectedRow];

Using Indexpath I got row.

If your table contains more that one section then you have to track the section also. For that you have to create an object of NSIndexPath .

@interface MyTableViewController : UITableViewController {
    NSIndexPath *obj_IndexPath;
}

and in implementation file,

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

       NSLog(@"%d",obj_IndexPath.row);
       NSLog(@"%d",obj_IndexPath.section);

}

and don't forget to release obj_IndexPath in dealloc method

I use this:

if(indexPath.row == 0){
   // do something...
  }else if(indexPath.row == 1){
   // do something else ...
 }

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