![](/img/trans.png)
[英]how can i create object of collectionview Cell in delegate sizeForItemAtIndexPath in swift
[英]Is it possible to get a cell's tag within the collectionview sizeForItemAtIndexPath delegate method?
当我调用以下委托方法时:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
float cellWidth = 90.0f; float cellHeight = 60.0f;
int cellType = [[collectionView cellForItemAtIndexPath:indexPath] tag];
return CGSizeMake(cellWidth, cellHeight);
}
cellType返回0。[collectionView cellForItemAtIndexPath:]也返回nil
我猜这是因为单元格没有设置大小,所以不显示,并且当不显示时,它返回nil(即,在创建单元格对象的实例之前调用此方法)。
有没有一种方法可以获取在collectionView:cellForItemAtIndexPath方法中为此项目设置的信息? 如何在sizeForItemAtIndexPath方法中标识单个单元格类型?
(我计划使用数据源NSArray,但我试图将这种逻辑保留在显示对象中,而不是由数据进行管理。)
在这里考虑做类似的事情:
var cell;
if let (cell = collectionView.cellForItemAtIndexPath(indexPath))
{
//get the cell's tag and do what is needed.
}
但我不知道cell是否会在sizeForCell方法中返回值
我不认为标签是可靠的,因为单元复用。 我建议使用与cellForItemAtIndexPath中使用的相同逻辑来标识NSArray中的数据。 然后根据数据确定要返回的大小。 换句话说,在cellForItemAtIndexPath和sizeForItemAtIndexPath中都依赖于您的数据源,而不是使sizeForItemAtIndexPath依赖于cellForItemAtIndexPath。
如果需要先获取单元,则需要将其出队。 因为layoutAttributesForItemAtIndexPath
将在itemAtIndexPath
之前被调用,这就是得到nil
的原因。
其次,仅当您重复使用该视图时,否则您将获得item的标签,否则所有视图都具有相同的标签0
。 但是,如果您知道哪个标识符用于使单元出队,请使用该标识符给出条件高度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.