问题:
I have a UITableView
with 5 UITableViewCells
. 我有一个UITableView
5个UITableViewCells
。 Each cell contains a UIButton
which is set up as follows: 每个单元格包含一个UIButton
,其设置如下:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier = @"identifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[UITableView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
[cell autorelelase];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, 40, 20)];
[button addTarget:self action:@selector(buttonPressedAction:) forControlEvents:UIControlEventTouchUpInside];
[button setTag:1];
[cell.contentView addSubview:button];
[button release];
}
UIButton *button = (UIButton *)[cell viewWithTag:1];
[button setTitle:@"Edit" forState:UIControlStateNormal];
return cell;
}
My question is this: in the buttonPressedAction:
method, how do I know which button has been pressed. 我的问题是:在buttonPressedAction:
方法中,我如何知道按下了哪个按钮。 I've considered using tags but I'm not sure this is the best route. 我考虑过使用标签,但我不确定这是最好的路线。 I'd like to be able to somehow tag the indexPath
onto the control. 我希望能够以某种方式将indexPath
标记到控件上。
- (void)buttonPressedAction:(id)sender
{
UIButton *button = (UIButton *)sender;
// how do I know which button sent this message?
// processing button press for this row requires an indexPath.
}
What's the standard way of doing this? 这样做的标准方法是什么?
Edit: 编辑:
I've kinda solved it by doing the following. 我通过以下方式解决了这个问题。 I would still like to have an opinion whether this is the standard way of doing it or is there a better way? 我仍然想知道这是标准的做法还是有更好的方法?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier = @"identifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[UITableView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
[cell autorelelase];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, 40, 20)];
[button addTarget:self action:@selector(buttonPressedAction:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button];
[button release];
}
UIButton *button = (UIButton *)[cell.contentView.subviews objectAtIndex:0];
[button setTag:indexPath.row];
[button setTitle:@"Edit" forState:UIControlStateNormal];
return cell;
}
- (void)buttonPressedAction:(id)sender
{
UIButton *button = (UIButton *)sender;
int row = button.tag;
}
What's important to note is that I can't set the tag in the creation of the cell since the cell might be dequeued instead. 需要注意的是,我无法在创建单元格时设置标记,因为单元格可能会出列。 It feels very dirty. 感觉很脏。 There must be a better way. 肯定有更好的办法。
解决方案:
参考一: https://en.stackoom.com/question/7Yxv参考二: https://stackoom.com/question/7Yxv