[cell addSubview:button]和[cell.contentview addSubview:button



我在tableviewcell中有按钮。[cell addSubview:button][cell.contentview addsubview:button]之间的区别是什么?因为当我在表视图中使用[cell addSubview:button]时,按钮功能可以很好地工作,但我在表中的界面搞砸了,当我在视图中滚动并返回到表视图后,按钮会转到左侧单元格。另一方面,当我使用[cell.contentview addsubview:button]按钮时,功能不起作用,也没有保存到myarray。

按钮代码:

UIButton *button=(UIButton *) [cell viewWithTag:103];//fav
[button setImage:[UIImage imageNamed:@"unfav.png"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"fav.png"] forState:UIControlStateSelected];
 button.frame = CGRectMake(0,0, 50, 50);
button.tag = indexPath.row;
[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:button]; // add the button to the cell
[cell bringSubviewToFront:button];

contentView是添加了所有subviews的单元格的默认视图。cell.view是添加了contentView本身和cell的主视图。contentView覆盖了cell.view的整个区域。但在您的情况下,当您将按钮添加到cell.view.时

来自苹果关于ContentView、的文档

UITableViewCell对象的内容视图是单元格显示内容的默认SuperView。如果您想通过简单地添加其他视图来自定义单元格,则应将它们添加到内容视图中,以便在单元格转换到编辑模式或从编辑模式转换到其他模式时对它们进行适当定位。

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewCell_Class/#//apple_ref/occ/instp/UITableViewCell/contentView

最新更新