[英]On iOS, what is the difference between adding a subview to a UITableViewCell object “cell” vs to “cell.contentView”?
In the following code, if we do [cell addSubview: someLabel]
vs [cell.contentView addSubview: someLabel]
, they seem to work the same.在下面的代码中,如果我们执行
[cell addSubview: someLabel]
与[cell.contentView addSubview: someLabel]
,它们似乎工作相同。 Is there any difference doing one or the other?做一个或另一个有什么区别吗? (the custom cell in the real code is adding
UIImageView
and UILabel
) ( UIView
, on the other hand, doesn't have contentView
, so we don't need to add subview to its contentView
. UITableViewCell
is a subclass of UIView
by the way) (实际代码中的自定义单元格是添加
UIImageView
和UILabel
)(另一方面, UIView
没有contentView
,所以我们不需要在它的contentView
添加子视图。顺便说一下, UITableViewCell
是UIView
的子类)
-(UITableViewCell *) tableView:(UITableView *) tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = nil;
if ([tableView isEqual:self.songsTableView]){
static NSString *TableViewCellIdentifier = @"MyCells";
cell = [tableView dequeueReusableCellWithIdentifier:TableViewCellIdentifier];
if (cell == nil){
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:TableViewCellIdentifier];
}
// ... some code to create a UILabel (not shown here)
[cell addSubview: someLabel]; // vs using [cell.contentView addSubView: ...]
I believe If I am not wrong, the contentView is a subview of UITableViewCell.我相信如果我没记错的话,contentView 是 UITableViewCell 的一个子视图。
If you look at this page here , you can see there are actually 3 subviews in a UITableViewCell如果您在此处查看此页面,您会看到 UITableViewCell 中实际上有 3 个子视图
I think by default, the Editing Control is hidden until you enter edit mode for a table in which case, the Editing Control appears (the minus button left of each row) and your contentView gets resized and pushed to the right.我认为默认情况下,编辑控件是隐藏的,直到您进入表格的编辑模式,在这种情况下,编辑控件出现(每行左侧的减号按钮)并且您的 contentView 被调整大小并推到右侧。 This is probably what gives the "proper animation" effect mentioned by the other answer.
这可能是另一个答案提到的“适当的动画”效果的原因。
To test the difference, try adding a subview such as UILabel with text, to the cell rather than the cell.contentView.要测试差异,请尝试将子视图(例如带有文本的 UILabel)添加到单元格而不是 cell.contentView。 When you add it to cell rather than cell.contentView and you enter edit mode for your table, I believe your UILabel will not resize, you will see the edit button ontop/below the minus sign button.
当您将其添加到单元格而不是 cell.contentView 并进入表格的编辑模式时,我相信您的 UILabel 不会调整大小,您会在减号按钮的顶部/下方看到编辑按钮。
Placing your views in the contentView
affects proper animation in and out of edit mode.将您的视图放在
contentView
会影响进入和退出编辑模式的正确动画。 Place all of your subviews in contentView
when you're not subclassing, which should be all of the time unless you know what you're doing.当您不进行子类化时,将所有子视图放在
contentView
,除非您知道自己在做什么,否则应该一直如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.