我有一个UICollectionView,它从可重用的单元格加载单元格,其中包含标签.数组为该标签提供内容.我可以使用sizeToFit轻松调整标签宽度,具体取决于内容宽度.但我不能让细胞贴合标签.
这是代码
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrayOfStats = @[@"time:",@"2",@"items:",@"10",@"difficulty:",@"hard",@"category:",@"main"];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection: (NSInteger)section{
return [arrayOfStats count];
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake(??????????);
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
Cell *cell = (Cell *) [collectionView dequeueReusableCellWithReuseIdentifier:@"qw" forIndexPath:indexPath];
cell.myLabel.text = [NSString stringWithFormat:@"%@",[arrayOfStats objectAtIndex:indexPath.item]];
// make label width depend on text width
[cell.myLabel sizeToFit];
//get the width …Run Code Online (Sandbox Code Playgroud) 如何正确调整UICollectionView的大小以使其完全显示其内容?我尝试了很多东西,包括设置框架,调用reloadData和使布局无效:
self.collectionView.contentSize = CGSizeMake(300, 2000);
self.collectionView.frame = CGRectMake(0, 0, 300, 2000);
[self.collectionView reloadData];
[self.collectionView.collectionViewLayout invalidateLayout];
Run Code Online (Sandbox Code Playgroud)
但这些都没有任何影响.按下按钮后,我仍然看到初始视图,如下所示:

我有一个小的演示程序,我有一个产生100个元素的数据源.在Interface Builder中,我最初将UICollectionView的大小设置为一个较小的值,以便不是所有元素都适合,之后我按下一个按钮,然后执行上面的代码.我希望UICollectionView现在显示所有元素,但事实并非如此.
编辑:演示程序可以在https://github.com/mjdemilliano/TestUICollectionView找到.
编辑2:我观察到帧更新在某些时候丢失,因为如果我再次按下按钮,当前帧将回到旧值.在按钮事件处理程序中添加一些日志语句后,日志输出为:
before: frame = {{0, 58}, {320, 331}}, contentSize = {320, 1190}
update button pressed
after: frame = {{0, 0}, {300, 2000}}, contentSize = {300, 2000}
before: frame = {{0, 58}, {320, 331}}, contentSize = {320, 1190}
update button pressed
after: frame = {{0, 0}, {300, 2000}}, contentSize = {300, 2000}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么不保留框架更改,改变它的原因.
在某些时候,我将用流布局中获得的值替换硬编码值,但我想排除这一点,并尽可能简单地保持我的示例.
上下文:我最终想要做的是:我有一个可滚动的视图,包含标签和图像等各种控件,以及一个包含动态内容的集合视图.我想滚动所有这些,而不仅仅是集合视图,因此我没有使用集合视图自己的滚动工具,它工作正常.
我有一个UICollectionView,一个在集合视图中创建新单元格的按钮.我希望UICollectionView根据它的内容大小调整它的大小(当有一个或两个单元格时,那么UICollectionView很短,如果有很多单元格UICollectionView足够大).
我知道如何获取内容大小:
collectionView.collectionViewLayout.collectionViewContentSize
但我不知道在哪里使用这个值.如果有人帮我弄清楚如何让UICollectionView自动调整它的高度,我将不胜感激.
UPD:我在GitHub上发布了一个描述问题的演示项目:https://github.com/avokin/PostViewer
我必须UICollectionView在 a 内添加一个UITableViewCell. 它们collectionView可以有不同数量的项目。所以collectionView应该在里面适当调整tableView。
我已经在我的项目中实现了这个: https ://github.com/vishalwaka/DynamicCollectionViewInsideTableViewCell
collectionView就我而言,设置单元格的高度后不会调整单元格的高度。
如何设置collectionView不可滚动并显示tableviewcell.