問題:
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