【问题标题】:help on button.tag = indexPath.row关于 button.tag = indexPath.row 的帮助
【发布时间】:2011-04-13 16:15:47
【问题描述】:

我的 cellForRowAtindexPath 上有这段代码,每个单元格上有一个自定义单元格和一个按钮。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 静态 NSString *MyIdentifier = @"tblCellView"; TableCellView *cell = (TableCellView *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 警报 *alarma = (Alarms *)[alarmsArray objectAtIndex: indexPath.row]; 如果(!单元格){ [[NSBundle mainBundle] loadNibNamed:@"TableCellView" owner:self options:nil]; 细胞 = tblCell; UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(-7, 4, 30, 33)]; [按钮 addTarget:self action:@selector(favButtonAction:) forControlEvents:UIControlEventTouchUpInside]; [按钮设置标签:1]; [cell.contentView addSubview:button]; [按钮释放]; } // 设置单元格。 [cell setLabelText: [alarma nombreAlarma]]; UIButton *button = (UIButton *)[cell viewWithTag:1]; button.tag = indexPath.row; 返回单元格; }

我的问题是,当我点击按钮时,我得到了随机结果,只要我在表格上移动并且单元格正在重用,我就会得到不同的索引,这些索引不等于相关单元格的标签 tex。

-(IBAction)favButtonAction: (id)sender { UIButton *button = (UIButton *)sender; 警报 *alarma = (Alarms *)[alarmsArray objectAtIndex: button.tag]; NSLog(@"labelText: %@",[alarma nombreAlarma]); }

例如,第一个单元格总是没问题,但最后一个单元格等于第一个 objectAtIndex(也许 button.tag 等于 0,而它必须是 14?)

【问题讨论】:

标签: iphone uitableview


【解决方案1】:

不要将按钮的标签值放在单元格内。

这是我的单元格内容视图中的按钮。注意:按钮应该是 Contentview 的子视图。

[cell1.YourButton addTarget:self action:@selector(OnClickCategory:) forControlEvents:UIControlEventTouchUpInside];

按钮的操作

- (void) OnClickCategory:(id) sender {

//NSIndexPath *indexPath =(NSIndexPath *)[sender tag];

UIView *senderButton = (UIView*) sender;
NSIndexPath *indexPath = [CategoryTable indexPathForCell: (UITableViewCell*)[[senderButton superview]superview]];

NSLog(@"%d",indexPath.row);

}

这对我有用。

【讨论】:

    【解决方案2】:

    好的,我找到了一个解决方案,是一种不同的方法,但它有效:

    [按钮 addTarget:self action:@selector(checkButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];

    然后在按钮处理程序上:

    - (void)checkButtonTapped:(id)sender 事件:(id)event { NSSet *touches = [事件 allTouches]; UITouch *touch = [触摸任何对象]; CGPoint currentTouchPosition = [触摸 locationInView:self.tableView]; NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition]; if (indexPath != nil) { ... } }

    更多信息在这里Detecting which UIButton was pressed in a UITableView

    【讨论】:

    • @david 谢谢你发布这个!!它为我节省了很多时间。
    猜你喜欢
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多