본문 바로가기

Swift/UIKit

높이가 다른 이미지 다운로드 후 Cell에 할당

    struct SectionInfoEntity {
        let imageUrl: String?
        var cellHeight: Double
	}

 

Entity가 cellHeight변수를 가지고 있음

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return self.sections[safe: indexPath.row]?.cellHeight ?? 0.0
    }

 

entity에 저장된 height로 cell 높이 지정

    private func imageSectionCell(tableView: UITableView, indexPath: IndexPath, sectionInfo: DisplayEventDetailEntity.SectionInfo) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "\(DiplayEventDetailImgSectionTVCell.self)") as? DiplayEventDetailImgSectionTVCell else {
            return UITableViewCell()
        }
        
        //KingFisher를 이용해 이미지를 다운 받은 뒤 completion 내부에서 cell높이 처리
        cell.eventImgView.kf.setImage(with: sectionInfo.imageUrl?.encodingURL) { [weak self] result in
            switch result {
            case .success(let value):
                let ratio = UIScreen.main.bounds.width / value.image.size.width
                let imageHeight = value.image.size.height * ratio
                self?.sections[indexPath.row].cellHeight = imageHeight //위 두 줄의 코드로 높이 계산후 entity에 저장
                cell.setCellContents(sectionInfo: sectionInfo)
                tableView.reloadRows(at: [indexPath], with: .none)
            case .failure(_):
                return
            }
        }
        return cell
    }

 

이미지 다운로드 이후 화면 비율로 이미지를 표시할 이미지뷰의 높이 계산해 entity에 저장

이미지 할당 후 해당 cell reload

 

즉, 'entity의 height으로 cell 높이 지정 (없으면 0) -> '이미지 다운로드 후 높이 계산해 entity에 저장' -> '해당 이미지 cell reload' -> 'reload로 인해 entity의 height으로 cell높이 지정' ->.... 반복

 

 

이렇게 다운로드 된 이미지의 높이별로 표시는 잘 된다

다만 단점은 다른 추가적인 cell이 있다면 그 cell의 높이도 계산해서 entity에 추가해줘야 한다는점...