아삭아삭 iOS 개발

[Swift] tableview cell 접었다 폈다 기능 구현하기_AutomaticDimension 본문

Swift

[Swift] tableview cell 접었다 폈다 기능 구현하기_AutomaticDimension

바닐라머스크 2022. 8. 14. 01:28

 

과제진행 중 tableviewcell을 접었다 폈다 하는 기능을 구현할 일이 있었습니다!

오늘은 그 구현과정을 정리하고 복습해보겠습니다~

(8/8 학습내용 중 일부 : )

 

구현하고자 했던 기능
tv 프로그램의 overview가 들어가는 section에서 셀을 접었다 폈다하는 기능으로 보여주고자 함.

그리고 셀을 펼쳤을 때 overview내용의 양에 따라서 그 셀의 길이를 동적으로 구현하고자 했음

 

완료모습


 

Setp1) DetailViewController에 접었다폈다 상태를 구분해줄 bool값 변수를 생성함

var isExpanded = false

 

 

Setp2) viewDidLoad() 안에 rowHeight을 설정해주는 아래코드 추가.

근데 어차피 나중에 heightForRowAt에서도 automaticDimension를 설정해주는데 굳이 여기서도 할 필요가 있을까 싶어서 아래 코드를 잠시 주석처리하고 실행해보았는데, 차이가 없었다!

자료를 찾아보니, 우선 테이블뷰의 모양이 다 잡히고 나서 그 다음에 automaticDimension이 적용되기 때문이라고 한다.

tableView.rowHeight = UITableView.automaticDimension

 

 

Setp3) (cell 코드파일) 접었다 폈다 기능을 담당해줄 버튼의 UI와 함수연결 통로(?)를 설정해줌

@IBOutlet weak var expandButton: UIButton!
var expandButtonTapped : (() -> Void) = {}

func configureButton() {
    expandButton.tintColor = .darkGray
    expandButton.backgroundColor = .clear
    expandButton.addTarget(self, action: #selector(expandCell), for: .touchUpInside)
}

@objc func expandCell() {
    expandButtonTapped()
}

 

 

Setp4) (다시 tableview쪽 뷰컨으로 넘어와서) cellForRowAt내 overViewcell 설정하는 곳에 아래 코드를 추가한다

- isExpanded 참/거짓에 따라 변할 버튼의 이미지 설정

- 버튼 클릭시마다 호출될 expandButtonTapped 안에서의 참/거짓 토글로직을 클로저 형태로 담아줌

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if indexPath.section == 0 {
        let overViewCell = tableView.dequeueReusableCell(withIdentifier: OverViewTableViewCell.reuseIdentifier, for: indexPath) as! OverViewTableViewCell
            
        overViewCell.overViewLabel?.text = list2[row].overview
        overViewCell.overViewLabel.numberOfLines = isExpanded ? 0 : 2
            
         if self.isExpanded {
            overViewCell.expandButton.setImage(UIImage(systemName: "chevron.up"), for: .normal)
        } else {
            overViewCell.expandButton.setImage(UIImage(systemName: "chevron.down"), for: .normal)
        }
            
        overViewCell.expandButtonTapped = {
            self.isExpanded = !self.isExpanded
            print(self.isExpanded)
            self.tableView.reloadData()
        }
        return overViewCell

// 이하생략

 

 

Setp5) heightForRowAt 설정함수에서 테이블뷰의 section에 따른 높이를 설정해줌.

이 때 overViewcell에 해당하는 section == 0 에서는 UITableView.automaticDimension. 

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return indexPath.section == 0 ? UITableView.automaticDimension : 100
}

 

 

이렇게 하면 끝!

...일 줄 알았는데 시뮬레이터를 돌렸더니, label line 라인 줄 수는 변하는게 보였지만

overview cell의 section 자체크기 변하지 않았다ㅠㅠ

 

왜그럴까 생각해봤더니 셀 자체내부 버튼의 레이아웃 제약 설정이 부족해서 그런거였다.

그래서 버튼의 위아래 제약조건을 아예 고정으로 설정했더니 해결!!

(수정하기 전에는 버튼의 top, bottom 둘 중 하나를 ≥로 설정했었다.)

 

 

 

위에 설정까지 해주고 났더니, 접었다폈다 완료~!! :)

접었다가 폈다가

 

(전체코드 보러가기 : https://github.com/minhye9731/SeSACTMDBProject/blob/main/SeSACTMDBProject/Controllers/DetailViewController.swift)