[iOS]- Self-SizingCell

Din의 개발노트·2021년 4월 17일
0

1. Self-SizingCell

  • 내용에 따라서 셀 높이를 자동으로 계산하는 방법과 셀 높이를 직접 설정하는 방법에 대해 알아보도록 하겠습니다.
  • iOS 8.0버전 이전과 이후를 비교해보겠습니다.
  • TableView는 Cell에 표시되는 내용을 기반으로 높이를 자동으로 계산합니다. 이 기능을 Self- Sizing이라고 합니다.
import UIKit

class ViewController: UIViewController {
    
    var list = [String]()
    
    @IBOutlet weak var listTableView: UITableView!
    @IBAction func add(_ sender: Any) {
        let alert = UIAlertController(title: "목록 입력", message: "추가할 글을 입력하세요", preferredStyle: .alert)
        
        alert.addTextField { (tf) in
            tf.placeholder = "내용을 입력하세요"
        }
        
        let okAction = UIAlertAction(title: "OK", style: .default) { (_) in
            if let title = alert.textFields?[0].text {
                self.list.append(title)
                self.listTableView.reloadData()
            }
        }
        
        let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        
        alert.addAction(okAction)
        alert.addAction(cancel)
        
        present(alert, animated: true, completion: nil)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        
        let target = list[indexPath.row]
        cell.textLabel?.text = target
        return cell
    }
}

이상태는 현재 새로운 글 목록을 추가할 수 있도록 구현되어있습니다.
이 상태에서 긴 글을 추가하면 글이 다 보이지 않는 현상이 발생합니다.

optional func tableView(_ tableView: UITableView, 
         heightForRowAt indexPath: IndexPath) -> CGFloat

높이를 제어해주는 메소드를 추가해주겠습니다.

profile
iOS Develpoer

0개의 댓글