🍎 IOS/UIKit

[iOS/UIKIt] UItableViewcell 간 간격 띄우기 (Section header 이용)

콩리또 2022. 9. 16. 14:50

안녕하세요 콩리또입니다 🌯

요즘 노션에 정리하느라 블로그가 뜸했었는데.. 

노션이 무료 요금제 용량이 다 차서.. 다시 블로그로 돌아오려고 합니다..

 

오늘은 제가 두번째 프로젝트를 하면서 어려웠던

tableView cell 간격 띄우기에 대해 말하는 시간을 가져보겠습니다.

모든 포스팅 말투는 편한 말투로 작성합니다!

피드백은 댓글로 부탁드려요!

감사합니다🥰

 


 

🤔  배경 및 문제 상황

목록을 추가 편집할 수 있는 List를 구현해야했는데

이때는 UIKit을 처음 접한 상황이라서 tableView를 사용하면 편집(추가,삭제)기능을 사용할 수 있다는 말만 듣고

무작정 tableView를 사용해서 구현하던 중이였음

 

그러다가 문제가 발생함..❗️

List 간의 간격을 띄어야하는데 tableView의 cell을 띄우는 기능이 없어서 꼼수로 제작해야했던 것

인터넷에는 UItableViewcell 간의  간격을 주려면 Cell에 inset 주면 된다고 했는데...

막상 구현해 보니 셀 안의 여백이 늘어남..🙃 그래서 다른 방법을 찾아 나서기 시작..

 

👉 Cell을 띄우기 위해 참고한 코드

// UITableViewCell을 상속받은 custom cell에서 layoutSubviews메소드 override

override func layoutSubviews() {
    super.layoutSubviews()

    contentView.frame = contentView.frame.inset(by: UIEdgeInsets(top: 16.0, left: 16, bottom: 16, right: 16))
}

출처 : https://ios-development.tistory.com/655

 

👉 결과

Cell을 띄우기 위해 내가 작성한 코드

 

(좌) contentView.frame.inset을 안줌 / (우)contentView.frame.inset 값 준 후 안쪽 여백이 늘어남

 


 

💡 해결 방법

결론을 먼저 말하자면 TableViewCell 간에 간격설정하는 방식을 찾지 못해

꼼수로 행을 row가 아닌 Section으로 구현해 Section header 영역에 간격을 줌

일단 간격이 들어가서 좋긴한데.. 치명적 단점은 최소 간격을 조절하지 못함..🥹

다음에는 List를 만들때 TableView는 꼭 필요할때만 만들어야겠다는 교훈을 얻음

 

👉 Section header을 이용해 tableView cell 간격조절

한 Section 당 하나의 행이 들어가고 Section header 영역을 투명으로 구현해 간격이 있는거처럼 보이는 것..!
// MARK: - UITableVIewDataSource
extension CategoryListViewController: UITableVIewDataSource {

	// UITableVIew 행의 갯수
    func numberOfSections(in tableView: UITableView) -> Int {
        return categories.count
    }
	
    // Section당 하나의 행만 들어감
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! CustomTableCell
        cell.categoryInfo = categories[indexPath.section]
        cell.cellDelegate = self
        cell.moreButton.tag = indexPath.section
        return cell
    }
}


// MARK: - UITableViewDelegate
extension CategoryListViewController: UITableViewDelegate {

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }

	//Section header의 높이를 정해줌(최소값을 줌)
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        let headerHeight: CGFloat = CGFloat.leastNormalMagnitude
        return headerHeight
    }
	
    // Section header를 투명색으로 줘 간격처럼 보이게 해줌
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView()
        headerView.backgroundColor = UIColor.clear
        return headerView
    }
}