본문 바로가기
이모저모/UIKit

테이블 셀 내부 UIButton에 addTarget을 계속 해도 되는이유

by ARpple 2023. 8. 1.

결론

💡 버튼이 갖는 target들의 정보는 Set으로 저장하기 때문에 중복되는 Target은 추가하지 않는다.

궁금증

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell: CustomTableViewCell = tableView.dequeueReusableCell(withIdentifier: CustomTableViewCell.identifier) as? CustomTableViewCell else {
            print("발생하지 않음")
            return UITableViewCell()
        }
        guard let row = self.info.list[safe:indexPath.row] else { return cell }
        cell.configureCell(item: row)
        cell.likeBtn.tag = indexPath.row
        cell.likeBtn.addTarget(self, action: #selector(Self.likeBtnTapped), for: .touchUpInside)
        return cell
    }
💡 위 코드는 버튼의 테그를 이용해서 addTarget한 버튼 액션 함수를 해당 셀의 모델과 뷰에 맞게 실행시키는 로직이다. addTarget을 계속 버튼에 실행할 함수를 쌓아서 결국 버튼을 한번 탭 하면 위에 `Self.likeBtnTapped`가 연속으로 실행되야하는 것이 아닌지 궁금해 디버그 로직을 만들어서 실행해봤다.

디버그 실험

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell: CustomTableViewCell = tableView.dequeueReusableCell(withIdentifier: CustomTableViewCell.identifier) as? CustomTableViewCell else {
            print("발생하지 않음")
            return UITableViewCell()
        }
        guard let row = self.info.list[safe:indexPath.row] else { return cell }
        cell.configureCell(item: row)
        cell.likeBtn.tag = indexPath.row
        print("셀 정보: \(cell)")
        print("셀 row: \(indexPath.row)")
        cell.likeBtn.addTarget(self, action: #selector(Self.likeBtnTapped), for: .touchUpInside)
        print("셀 버튼이 갖고 있는 Target 계수 \(cell.likeBtn.allTargets)")
        print("--------------------------")
        return cell
    }

이 로직을 갖고 테이블을 스크롤 한 후 cell 값을 추적했다.

⚠️ 재사용 Cell이 갖고 있는 Target은 계속 하나로 유지되었다..!

댓글