관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] self resizing cell, dynamic cell, flexible cell (cell크기에 따라 자동으로 cell height 조정, stackView 이용) 본문

iOS 응용 (swift)

[iOS - swift] self resizing cell, dynamic cell, flexible cell (cell크기에 따라 자동으로 cell height 조정, stackView 이용)

jake-kim 2021. 9. 13. 01:15

stackView를 이용하여 self-resizing cell 구현 

stackView를 이용하여 self-resizing-cell 구현 방법

  • cell을 선택하면 stackView에 있는 star imageView를 hidden = false하여 생성되게끔 설정
override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    updateSelectedCell(selected)
}

private func updateSelectedCell(_ selected: Bool) {
    imageContainerView.isHidden = !selected
}
  • tableView의 delegate 설정
    • 주의: tableView(_:heightForRowAt:)에서 특정 값을 리턴하면 cell의 높이값이 고정되므로 아예 메소드 선언 x
    • 설정해주어야 하는것: tableView(_:didSelectRowAt:)tableView(_:didDeselectRowAt:)두 메소드에서 아래 메소드 호출
      • 선택할 때 - didSelectRowAt
      • 선택을 해제할 때 - didDeselectRowAt
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.beginUpdates()
    tableView.endUpdates()
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    tableView.beginUpdates()
    tableView.endUpdates()
}
  • beginUpdates(): endUpdates()와 함께 사용하여 cell을 reloading없이도 cell의 row height에 관한 변경 애니메이션을 적용할때 사용

주의

  • stackView의 특성: stackView에 특정 뷰가 추가되거나 삭제될 때, 먼저 stackView의 크기가 조정된 다음 view가 삭제되거나 추가되므로, 애니메이션에 주의

duration을 3초로 준 경우

  • estimatedRowHieght: estimatedRowHeight는 셀의 height의 단순 추정치이며, 내부적으로 cell의 높이를 계산할때 대략적인 값으로 참고하여 성능을 높이는데 사용
// 프로퍼티 사용
tableView.estimatedRowHeight = 42.0

// 메소드 사용
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return 42.0
}

estimatedRowHieght

  • rowHeight: UITableView.automaticDimension은 cell 내부 컨텐츠의 크기만큼 자동으로 cell의 height크기를 늘리거나 줄어들게 해주는 옵션
// 프로퍼티 대입
tableView.rowHeight = UITableView.automaticDimension

// 메소드 사용
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

 

* 전체 소스코드: https://github.com/JK0369/TableViewCellEx

* 참고

- estimatedRowHieght: https://developer.apple.com/documentation/uikit/uitableview/1614925-estimatedrowheight

- beginUpdates(): https://developer.apple.com/documentation/uikit/uitableview/1614908-beginupdates

- endUpdates(): https://developer.apple.com/documentation/uikit/uitableview/1614890-endupdates

Comments