【问题标题】:Call didSelectRowAtIndex for Custom Cell为自定义单元格调用 didSelectRowAt 索引
【发布时间】:2014-10-06 02:47:19
【问题描述】:

我有一个单元格,它有两个 UIButton 属性(nameLabel 和 profileImageButton),用于查看帖子的用户个人资料页面。我试图从当前单元格中获取用户,但没有调用 didSelectRowAtIndex。我意识到这应该会发生(没有调用该方法),但我不知道如何解决它。

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

cell.personStringPost.text = [object objectForKey:@"stringPost"];
[cell.nameLabel setTitle:[object objectForKey:@"User_Name"] forState:UIControlStateNormal];
cell.userId = [object objectForKey:@"userId"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;

PFFile *imageFile = [object objectForKey:@"profileImage"];
NSData *data = [imageFile getData];
cell.profileImage.image = [UIImage imageWithData:data];

cell.nameLabel.tag = indexPath.row;
[cell.nameLabel addTarget:self action:@selector(buttonPressed:) forControlEvents: UIControlEventTouchUpInside];
[cell.profileImageButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[super tableView:tableView didSelectRowAtIndexPath:indexPath];
postCell *cell = (postCell *)[tableView cellForRowAtIndexPath:indexPath];
self.userId = cell.userId;
NSLog(@"Did Select: %@", self.userId);
}

- (void) buttonPressed: (id) sender{
UIButton *button = (UIButton *)sender;
NSInteger row = button.tag;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
[self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
[self performSegueWithIdentifier:@"personProfile" sender:self];
}

【问题讨论】:

  • 为什么要调用 didSelectRow,因为无论如何你都在按钮方法中进行 segue?
  • 如果你知道“当前单元格”是什么,你就不能从中获取用户吗?
  • 因为我需要将数据从当前单元格传递到下一个视图控制器。而且我不知道当前的单元格是什么,那是我的问题。当我按下按钮时没有调用 didSelectRowAtIndexPath 所以我不知道单元格数据是什么@HotLicks
  • @rdelmar 我需要从所选单元格中获取数据
  • 您不应该从单元格中获取数据。您的按钮标签为您提供了被选中的行。您应该将其用作用于填充表格的数组的索引。

标签: ios xcode uitableview uibutton


【解决方案1】:
- (void)selectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UITableViewScrollPosition)scrollPosition;
- (void)deselectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated;

// 选择和取消选择行。这些方法will not call委托方法(-tableView:willSelectRowAtIndexPath: or tableView:didSelectRowAtIndexPath:),也不会发出通知。

所以将 buttonPressed 中的 selectRowAtIndexPath 替换为以下两行:

postCell *cell = (postCell *)[tableView cellForRowAtIndexPath:indexPath];
self.userId = cell.userId;

【讨论】:

  • 非常糟糕的做法。应该从 dataSource 访问 userId。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多