UIButton 在自定义单元格中更改
Posted
技术标签:
【中文标题】UIButton 在自定义单元格中更改【英文标题】:UIButton changing in custom cell 【发布时间】:2013-11-09 12:46:55 【问题描述】:我正在使用此代码更改我的UITableView
中的UIButton
。
问题是当我滚动时,表格的按钮会无缘无故地发生变化。
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(232, 88, 78, 24)];
if([[array objectAtIndex:(indexPath.row)] isEqualToString:@"0"])
[button setImage:[UIImage imageNamed:@"pic1"] forState:UIControlStateNormal];
else
[button setImage:[UIImage imageNamed:@"pic2"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[Cell.contentView addSubview:button];
这是buttonClicked:
方法:
-(void)buttonClicked:(id)sender
CGPoint touchPoint = [sender convertPoint:CGPointZero toView:self.myTableView];
NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:touchPoint];
UIButton *button = (UIButton *)sender;
if([[array objectAtIndex:indexPath.row] isEqualToString:@"0"])
[button setImage:[UIImage imageNamed:@"pic2"] forState:UIControlStateNormal];
[array replaceObjectAtIndex:indexPath.row withObject:@"1"];
else
[button setImage:[UIImage imageNamed:@"pic1"] forState:UIControlStateNormal];
[array replaceObjectAtIndex:indexPath.row withObject:@"0"];
【问题讨论】:
这是因为表格视图重用了它的单元格,您应该在委托方法tableview:cellforrowatindexpath:
中更新您的按钮状态或任何其他按钮的属性。
【参考方案1】:
那是因为您的单元格正在被重复使用。试试这个:
UIButton *button; = (UIButton *) [cell viewWithTag:34];
if (!button)
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(232, 88, 78, 24)];
button.tag = 34;
if([[array objectAtIndex:(indexPath.row)] isEqualToString:@"0"])
[button setImage:[UIImage imageNamed:@"pic1"] forState:UIControlStateNormal];
else
[button setImage:[UIImage imageNamed:@"pic2"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[Cell.contentView addSubview:button];
【讨论】:
还是不行,我按了button1,向下滚动,button5和button6变成了pic2。向上滚动,button1 变回了 pic1。 对不起,还是同样的问题。以上是关于UIButton 在自定义单元格中更改的主要内容,如果未能解决你的问题,请参考以下文章
使用自动布局在屏幕更改时调整自定义单元格中的 UIButton 字体
无法在自定义表格视图单元格中使 ImageView 成为一个圆圈