[231229] Today I Learned

YoungHyun Kim·2023년 12월 29일
1

TIL ✍️

목록 보기
28/68

1. 클로저를 사용한 TableView <-> TableViewCell 데이터 전달

  1. TableViewCell 클래스 내부에 구현하고 싶은 동작의 반환값을 가지는 클로저를 정의한다.
    var increaseButton: (() -> ())?

  2. 예시로 적은 코드에서 보다시피 버튼을 누르면 해당 클로저가 실행되도록 할 것이고, 이 내용을 @IBAction 함수 내부에 적으면 되지 않을까...

@IBAction func orderTableViewIncreaseButton(_ sender: UIButton) {
    increaseButton?()
}
  1. ViewController 에서 tableView(_ tableView:, cellForRowAt:) -> UITableViewCell 함수를 정의해서 각각의 cell을 그릴 때, cell 내부에 선언해둔 클로저에 동작을 할당해주면 버튼을 눌렀을 때 원하는 동작을 실행시킬 수 있다.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = OrderTableView.dequeueReusableCell(withIdentifier: "OrderTableViewCell", for: indexPath) as! OrderTableViewCell
    cell.increaseButton = { [weak self] in
        self?.customer.cart[indexPath.row].number += 1
        self?.OrderTableView.reloadData()
        self?.customer.calculateTotal()
        self?.totalPriceLabel.text = String(self?.customer.totalPrice ?? 0) + " 원"
        self?.totalQuantityLabel.text = String(self?.customer.totalQuantity ?? 0) + " 개"
    }
    return cell
}
profile
iOS 개발자가 되고 싶어요

0개의 댓글