2016-11-28 1 views
0

다음 코드를 사용하여 셀의 크기를 개별적으로 조정하려고합니다.동적으로 셀 크기를 조정하는 중 오류가 발생했습니다.

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 
} 
+0

@ 토마스 G. 응답 해 주셔서 대단히 감사합니다. 당신 말이 맞아 .. 내가 테스트 한 결과, customCell에 캐스팅 다운에 문제가있다. 그러나 나는 아직도 무엇이 잘못되었는지를 모른다. 편집 된 부분에 CellForItemAt 함수를 제공했습니다. 정말 고마워! – user3608914

답변

1

sizeForItemAt()cellForItemAt() 전에 호출되는 추가 CellForItemAt 기능.

난에 그 볼 당신의 cellForItemAt()하면, 이미지 크기를 잡기 위해 sizeForItemAt()에서 동일한 배열을 사용하는 것이 이미지에 대한 배열을 사용하는 예와 같이 볼 수 있었다 당신의 size FUNC의 시작 부분에 대한;

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 
    var itemSize : CGSize? 

    // delete this line** let currentCell = self.collectionView?.cellForItem(at: indexPath) as! CustomCell 
    // let imageSize : CGSize = (currentCell.imageView?.image?.size)! 
    let imageSize : CGSize = imageArray[indexPath.item].size // or indexPath.row depending on your structure 
    let aspectRatio : CGFloat = imageSize.width/imageSize.height 
    ... 
} 
+1

고마워, 사실 나는 그저 하하 .. 어쨌든 무엇이 잘못되었는지 생각하고 있었어.하지만 너는 정말 좋은 대답을했다. 고마워! (: – user3608914

관련 문제