在 UICollectionView 的 cell 中添加 subView 不显示的问题

2015-01-29 21:42:36 +08:00
 tsinghan

在cellForItemAtIndexPath方法中

var videoView = videos["video"] as UIView
videoView.frame = cell.frame
self.collectionView.addSubview(videoView)

如果我设置了 videoView.frame = cell.frame 这句,那么这个subview 就不会显示

我修改了frame(包含在cell中)

var videoView = videos["video"] as UIView
videoView.frame = videoView.frame = CGRect(x: 37, y: 94, width: 100, height: 100)
self.collectionView.addSubview(videoView)

这样就显示了

请问这是什么原因?

8100 次点击
所在节点    iDev
9 条回复
krafttuc
2015-01-29 22:36:49 +08:00
没看明白楼主为什么要在 collection view 里添加这些个 video view,而不是把他们放到 cell 里。
keithellis
2015-01-29 22:39:17 +08:00
自定义一个 UICollectionViewCell,在 layoutSubviews 方法中设置 frame,另外 subView 我一般放在 contentView 里。
mailworks
2015-01-29 22:57:13 +08:00
如楼上,自定义的View添加到UICollectionViewCell的contentView 中,
videoView.frame = cell.bounds这样设置
ruandao
2015-01-29 23:04:44 +08:00
把frame 打印出来~~
tsinghan
2015-01-29 23:11:53 +08:00
@krafttuc
@keithellis 抱歉我贴错代码了 我是放到 contentView里的 cell.contentView.addSubview(videoView)
tsinghan
2015-01-29 23:12:24 +08:00
@mailworks 恩 我试试这种方法
tsinghan
2015-01-29 23:26:51 +08:00
@krafttuc
@keithellis
@ruandao
@mailworks 恩 用videoView.frame = cell.bounds 这种方式设置确实可以显示了
我分别打印了 cell.bounds 和 cell.frame 分别为 (0.0,0.0,155.0,125.0) 和 (0.0,230.0,155.0,125.0)
而我cell的大小就是 (0.0,230.0,155.0,125.0) 这样的, 为什么要videoView.frame = cell.bounds 设置?没搞懂
vincentxue
2015-01-29 23:32:20 +08:00
我靠 我刚发现我写的回复怎么没出来。。。。。
重新贴一下吧还好我有剪贴板历史记录。

如果你一定要在这里添加子视图,那坐标应该这么写:

videoView.frame = cell.bounds;

如果是 tableView 要在 willDisplayCell 中设置 frame,因为 UITableViewCell 从初始化到显示之前都不知道自己的 frame 的,默认都是 CGRectZero。

但自定义 cell 通常应该子类化。

frame 是相对于父视图而言的,

假设有一个 UICollectionView, frame 为 {{0, 0}, {320, 480}};
假设 cell 大小是 {40, 40},间隙为 0, 0 的话,那么你屏幕上显示的第一行(8 个)的 cell 的 frame 应该如下:

0: {{0, 0}, {40, 40}}
1: {{40, 0}, {40, 40}}
2: {{80, 0}, {40, 40}}
3: {{120, 0}, {40, 40}}
4: {{160, 0}, {40, 40}}
5: {{200, 0}, {40, 40}}
6: {{240, 0}, {40, 40}}
7: {{280, 0}, {40, 40}}

你可以想象一下,如果你的父视图才 {40, 40},你自身的 frame.origin.x 或者 y 就超过 40 了,肯定是看不见的了。
tsinghan
2015-01-29 23:44:41 +08:00
@vincentxue 明白了 十分感谢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/166610

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX