我有一个简单的剖面表视图。我在图像的左侧添加了一个按钮。此按钮是可选择的。一次只能选择一个按钮(每个单元格具有相同类型的单个按钮),并且所选按钮背景图像将更改为特定的所选图像,其他按钮背景图像更改为取消选择图像。如果再次点击所选图像,它将保持选中状态。 我怎么没有得到正确的行为。 代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// UITableViewCell *cell=nil;
CustomCellMasterCustomer *cell=nil;
static NSString *cellIdentifier=@"Locations";
Customer *mCustomer;
cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell==nil){
// cell=[self reusableContentWithIdentifier:cellIdentifier];
cell=(CustomCellMasterCustomer *)[self reusableContentWithIdentifier:cellIdentifier];
}
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.tag = indexPath;
[button setBackgroundImage:[UIImage imageNamed:@"cellLeftImageDisabled.png"] forState:UIControlStateNormal];
[button setFrame:CGRectMake(10, 5, 36, 30)];
[button addTarget:self action:@selector(viewDetail:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button];
cell.aCustomer = mCustomer;//alok added
if (indexPath == self.mPreviousIndex)
{
[button setBackgroundImage:[UIImage imageNamed:@"cellLeftImageEnabled.png"] forState:UIControlStateNormal];
}
else
{
[button setBackgroundImage:[UIImage imageNamed:@"cellLeftImageDisabled.png"] forState:UIControlStateNormal];
}
return cell;
}
-(void)viewDetail:(id)sender
{
CGPoint buttonOrigin = [sender frame].origin;
// this converts the coordinate system of the origin from the button's superview to the table view's coordinate system.
CGPoint originInTableView = [self.allCustomerTable convertPoint:buttonOrigin fromView:[sender superview]];
// gets the row corresponding to the converted point
NSIndexPath *rowIndexPath = [self.allCustomerTable indexPathForRowAtPoint:originInTableView];
CustomCellMasterCustomer *cell = (CustomCellMasterCustomer *)[self.allCustomerTable cellForRowAtIndexPath:rowIndexPath];
[self fillDetailViewWithCustomerInformation:cell.aCustomer];
//change button background image
UIButton *btn = (UIButton *)sender;
[btn setBackgroundImage:[UIImage imageNamed:@"cellLeftImageEnabled.png"] forState:UIControlStateNormal];
self.mPreviousIndex = rowIndexPath;
[self.allCustomerTable reloadData];
}
我正在做什么错, 任何建议答案 0 :(得分:0)
试试这个。因为indexpath总是使用相同的行和节号重新创建。它与以前不一样。
if (indexPath.row == self.mPreviousIndex.row && indexPath.section == self.mPreviousIndex.section)
{
[button setBackgroundImage:[UIImage imageNamed:@"cellLeftImageEnabled.png"] forState:UIControlStateNormal];
}
这两行代码,不再需要了
/* UIButton *btn = (UIButton *)sender;
[btn setBackgroundImage:[UIImage imageNamed:@"cellLeftImageEnabled.png"] forState:UIControlStateNormal];*/
答案 1 :(得分:0)
您不应在if
块旁边添加按钮。在UITableView
单元格中将重复使用,如果单元格被重用,并且已经有一个按钮添加到contentView
,那么您不应再添加一个按钮。因此,通过在customCell.h
中声明buttion属性,创建一个自定义单元格并使该类实例在类外可见。现在检查条件 -
if (selected)
{
cell.button.backgroundImage = selectedImage;
}
else
{
cell.button.backgroundImage = unselectedImage;
}