개발/Swift

[Swift] UI - Dynamic TableView

Liber21 2022. 10. 29. 14:47
반응형

높낮이를 컨텐츠 사이즈에 따라 알아서 맞춰주는 테이블 뷰! 

 

CustomView 추가

import Foundation
import UIKit

class UIDynamicSizeTableView: UITableView {
    
    override var intrinsicContentSize: CGSize {
        let height = self.contentSize.height + self.contentInset.top + self.contentInset.bottom
        return CGSize(width: self.contentSize.width, height: height)
    }
    
    override func layoutSubviews() {
        self.invalidateIntrinsicContentSize()
        super.layoutSubviews()
    }
    
}

 

ViewController 에서 사용

import Foundation
import UIKit

class ViewController: UIViewController {
    
    ...
    
    private lazy var tableView = UIDynamicSizeTableView().then {
        $0.showsVerticalScrollIndicator = false
        $0.showsHorizontalScrollIndicator = false
    }
    
    ...
    
}

 

장점 : estimatedRowHeight, rowHeight 를 지정해줄 필요가 없음
단점 : 아직 찾지 못함 ☺️ 그러나 뷰 성격에 맞게 활용해야 장점을 발휘할 수 있음

반응형