다음 코드를 사용하여 셀의 크기를 개별적으로 조정하려고합니다.동적으로 셀 크기를 조정하는 중 오류가 발생했습니다.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
var itemSize : CGSize?
let currentCell = self.collectionView?.cellForItem(at: indexPath) as! CustomCell
let imageSize : CGSize = (currentCell.imageView?.image?.size)!
let aspectRatio : CGFloat = imageSize.width/imageSize.height
if aspectRatio > 1 {
itemSize = CGSize(width: self.maxItemSize.width, height: maxItemSize.height/aspectRatio)
}else{
itemSize = CGSize(width: self.maxItemSize.width * aspectRatio, height: maxItemSize.height)
}
return itemSize!
}
하지만 난 항상 치명적인 오류를 얻을 : 나는이 블록을 제거하면, 다른 한 후 모든 것이 완벽하게 작동
let currentCell = self.collectionView?.cellForItem(at: indexPath) as! CustomCell
이 줄에서 옵션 값을 풀기 동안 예기치 않게 누구나 무슨 일이 일어나고 있는지 알고 .. 전무 발견 에?
미리 감사드립니다.
편집 : 당신은 셀 (의 이미지 크기)에서 정보를 잡으려고 노력하고 있지만 세포가 아직 생성되지 않도록
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! CustomCell
cell.backgroundColor = colorArray[indexPath.section]
cell.imageView?.image = imageArray[indexPath.item]
return cell
}
@ 토마스 G. 응답 해 주셔서 대단히 감사합니다. 당신 말이 맞아 .. 내가 테스트 한 결과, customCell에 캐스팅 다운에 문제가있다. 그러나 나는 아직도 무엇이 잘못되었는지를 모른다. 편집 된 부분에 CellForItemAt 함수를 제공했습니다. 정말 고마워! – user3608914