我正在尝试创建一个可以从标签高度自动调整大小的集合视图。我有两个不同的单元格,其中一个带有照片,另一个没有照片,两个都在xib文件中。
我尝试了不同的方法使这个高度动态但没有解决方案((。
var CollectionViewCellNib = UINib(nibName: "CollectionViewCell", bundle: nil)
collectionView.registerNib(CollectionViewCellNib, forCellWithReuseIdentifier: "CollectionViewCell")
var CollectionViewCellWithPhotoNib = UINib(nibName: "CollectionViewCellWithPhoto", bundle: nil)
collectionView.registerNib(CollectionViewCellWithPhotoNib, forCellWithReuseIdentifier: "CollectionViewCell")
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let pikirler = self.pikirler[indexPath.row]
let targetWidth: CGFloat = (self.collectionView.bounds.width - 2 * kHorizontalInsets)
if indexPath.row == 2 {
var cell = self.offscreenCells[CollectionViewKeyWords.collectionViewOnlyTextCell] as? CollectionViewCell
if cell == nil {
cell = NSBundle.mainBundle().loadNibNamed("CollectionViewCell", owner: self, options: nil)[0] as? CollectionViewCell
self.offscreenCells[CollectionViewKeyWords.collectionViewOnlyTextCell] = cell
}
cell!.configCell("sometext", content: "sometext")
cell!.bounds = CGRectMake(0, 0, targetWidth, cell!.bounds.height)
cell!.contentView.bounds = cell!.bounds
cell!.setNeedsLayout()
cell!.layoutIfNeeded()
var size = cell!.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
size.width = targetWidth
return size
}else{
var cell = self.offscreenCells[CollectionViewKeyWords.collectioViewWithPhotoCell] as? CollectionViewCellWithPhoto
if cell == nil {
cell = NSBundle.mainBundle().loadNibNamed("CollectionViewCellWithPhoto", owner: self, options: nil)[0] as? CollectionViewCellWithPhoto
self.offscreenCells[CollectionViewKeyWords.collectioViewWithPhotoCell] = cell
}
cell!.configCell("Some text", content: "sometext")
cell!.bounds = CGRectMake(0, 0, targetWidth, cell!.bounds.height)
cell!.contentView.bounds = cell!.bounds
cell!.setNeedsLayout()
cell!.layoutIfNeeded()
var size = cell!.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
size.width = targetWidth
return size
}
}