contentView 子视图保持在屏幕上
在我的表格视图中,我将子视图添加到某个单元格中。如果单元格的数量大于一个屏幕的高度,例如,屏幕可以包含10个单元格,如果滚动到11个单元格,第一个单元格将消失。当返回顶部时,第一个单元格显示,但带有子视图,即使它没有单元格。
是因为子视图浮动吗?
In my tableview, I add subview into some cell. If the number of cell big than one screen's height, for example, the screen can contains 10 cells, if scroll to 11 cells, the first cell will disappear. When return to top, the first cell shows but with a subview even when it do not have cells.
Is it because the subview float?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为单元格被重用,以节省内存。当您滚动表格视图时,它将重用被推出屏幕的相同单元格。如果其中一些包含子视图,则子视图也可能被重用并显示在错误的位置。
如果您要将子视图添加到单元格的
contentView
中,请务必标记(UIView
中的tag
属性)视图并使用获取它们>[cell.contentView viewWithTag:YOUR_TAG_ID]
并对它们执行任何您想要的操作(即,如果子视图不应该位于新单元格中,则将其删除)。示例(其中在某些单元格中添加了
UITextField
):This is because the cells are being reused, in order to save memory. When you scroll your table view, it'll reuse the same cells that become pushed off screen. If some of them contained subviews, the subviews may also be reused and displayed at the wrong places.
If you're adding subviews to a cell's
contentView
, be sure to tag (tag
property inUIView
) the views and fetch them with[cell.contentView viewWithTag:YOUR_TAG_ID]
and do whatever you want with them (i.e. remove the subview if it's not supposed to be in your new cell).Example (where a
UITextField
is added in some cells):为了避免这种行为,您可以在添加新的子视图之前删除单元格的所有视图。
To avoid this kind of behaviour, you can remove all the views of your cell, before adding new subviews.
通过为每个单元格设置唯一的reuseIdentifier来修复,使得tableview不能重用单元格。我的表格视图应该是 100 行,所以看起来不错。
Fixed by set unique reuseIdentifier for every cell, so that tableview can not reuse cell. My table view should be in 100 line, so looks good.