UIKit. TableViewCell에 UITextView 넣고 동적으로 높이 변경하기

UITableViewCell 안에 UITextView를 넣고, 입력되는 텍스트 길이에 따라 셀의 높이가 자동으로 늘어나도록 처리했다. 처음에는 그냥 UITextView를 셀에 넣으면 알아서 늘어날 줄 알았는데, UITextView 자체의 스크롤과 UITableView의 셀 높이 계산이 같이 걸려 있어서 생각보다 손이 조금 간다ㅏ. 핵심은 UITextView의 스크롤을 끄고, 텍스트가 변경될 때 UITableView에 높이를 다시 계산하라고 알려주는 것이다. 구현 순서 1. UITextView에서 다음 속성들 체크 해제 Show Horizontal Indicator: 텍스트가 가로 크기를 초과한 경우, 가로 스크롤 바 표시 Show Vertical Indicator: 텍스트가 세로 크기를 초과한 경우, 세로 스크롤 바 표시 Scrolling Enabled: 스크롤 가능 여부 설정 Bounce on Scroll: 스크롤이 끝에 도달했을 때, 가볍게 튕기는 애니메이션 설정 2. Nib 등록 tableView.register( UINib(nibName: "GrowingCell", bundle: nil), forCellReuseIdentifier: "GrowingCell" ) 3. 데이터 소스 추가 extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell( withIdentifier: "GrowingCell", for: indexPath ) as? GrowingCell else { return UITableViewCell() } cell.textView.text = items[indexPath.row] cell.delegate = self return cell } } 4. 델리게이트 작성 protocol GrowingCellProtocol: class { func updateHeightOfRow(_ cell: GrowingCell, _ textView: UITextView) } 5. 뷰 컨트롤러가 델리게이트 채택하고 구현 extension ViewController: GrowingCellProtocol { func updateHeightOfRow(_ cell: GrowingCell, _ textView: UITextView) { let size = textView.bounds.size let newSize = tableView.sizeThatFits( CGSize( width: size.width, height: CGFloat.greatestFiniteMagnitude ) ) if size.height != newSize.height { UIView.setAnimationsEnabled(false) tableView?.beginUpdates() tableView?.endUpdates() UIView.setAnimationsEnabled(true) if let thisIndexPath = tableView.indexPath(for: cell) { tableView.scrollToRow(at: thisIndexPath, at: .bottom, animated: false) } } } } 추가. 공식 문서에서는 beginUpdates() 보다 performBatchUpdates(_:completion:) 의 사용을 권장하고 있음. ...

September 15, 2024

UIKit. UIStackView 레이아웃

UIStackView는 여러 뷰를 한 방향으로 묶어 배치할 수 있는 컨테이너 뷰다. 직접 서브뷰마다 제약 조건을 하나씩 걸지 않아도, 스택 뷰에 arranged subview로 추가하면 스택 뷰가 내부 뷰들의 배치를 관리한다. 스택 뷰는 기기의 방향, 화면 크기, 그리고 axis, alignment, distribution, spacing 같은 프로퍼티를 바탕으로 내부 뷰의 레이아웃을 결정한다. 이 글에서는 스택 뷰의 주요 프로퍼티가 레이아웃에 어떤 영향을 주는지 정리한다. intrinsicContentSize 스택 뷰의 레이아웃을 이해하려면 먼저 intrinsicContentSize를 알아야 한다. intrinsicContentSize는 뷰가 자신의 내용만을 기준으로 자연스럽게 가지는 크기다. 대표적인 예시는 UILabel이다. ...

August 27, 2024