iOS,如何findUITableView选定的行?
我试图find选定的UITableViewCell
如下:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } if ([indexPath row] == [tableView cellForRowAtIndexPath:indexPath.row]) // i want to place value of selected row to populate the buttons //([indexPath row] == 0) //(indexPath.row == ![self cellIsSelected:indexPath]) { UIButton *AddComment = [UIButton buttonWithType:UIButtonTypeCustom]; // custom means transparent it takes shape same with backgroup image [AddComment addTarget:self action:@selector(TestBtns:) forControlEvents:UIControlEventTouchDown]; // [AddComment setTitle:@"1" forState:UIControlStateNormal]; AddComment.frame = CGRectMake(9.0, 128.0, 96.0, 26.0); [cell.contentView addSubview:AddComment]; UIImage *buttonAddComment = [UIImage imageNamed:@"addcomment.png"]; [AddComment setBackgroundImage:buttonAddComment forState:UIControlStateNormal]; [cell.contentView addSubview:AddComment]; }
如何做到这一点,你可以请指导我,我在做错误的地方。
NSIndexPath *selectedIndexPath = [tableView indexPathForSelectedRow];
使用UITableView
这个委托方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"%d", indexPath.row); // you can see selected row number in your console; }
在UITableViewDataSource委托有一个方法– (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 。
它返回包含选定部分和选定行的NSIndexPath对象。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ NSLog(@"Selected section>> %d",indexPath.section); NSLog(@"Selected row of section >> %d",indexPath.row); }
确保在使用之前设置tableview的数据源,否则这个方法将不会被调用
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { int a = indexPath.row; NSLog(@"index: %i",a); }
这是内置的方法,可以帮助您确定select了哪个单元格。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // you can use "indexPath" to know what cell has been selected as the following NSLog(@"Selected row is %@", indexPath); }
顺便说一下,当你创buildTableViewController的时候,这个方法已经被提供了,你可能只需要取消它的注释。
希望你觉得有帮助
我认为你要做的是不要得到点击表格视图单元格的索引,但要知道哪个单元格被点击。
要知道这在分配每个单元格时分配indexpath.row值作为创build的单元格的标记,然后单击将表视图作为父级,并尝试使用该标记获取其子视图(单元格)
[带有标签的Tableview视图:indexpath.row]