UIKit. TableViewCell 스와이프 동작 넣기

기본 메소드들 // 오른쪽에서 왼쪽으로 스와이프 tableView(_:trailingSwipeActionsConfigurationForRowAt:) // 왼쪽에서 오른쪽으로 스와이프 tableView(_:leadingSwipeActionsConfigurationForRowAt:) 구현 순서 1. UIContextualAction을 사용해서 액션 구현 let deleteAction = UIContextualAction(style: .destructive, title: "삭제") { (action, view, completionHandler) in // 삭제 로직 completionHandler(true) } 2. UISwipeActionsConfiguration에 액션 등록 // 액션 여러개 등록 가능 let configuration = UISwipeActionsConfiguration(actions: [deleteAction]) 3. 전체 코드 func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let deleteAction = UIContextualAction(style: .destructive, title: "삭제") { (action, view, completionHandler) in // 삭제 로직 completionHandler(true) } let configuration = UISwipeActionsConfiguration(actions: [deleteAction]) configuration.performsFirstActionWithFullSwipe = false return configuration } 기타 색깔, 이미지 지정 가능 deleteAction.backgroundColor = .systemRed deleteAction.image = UIImage(systemName: "trash") performsFirstActionWithFullSwipe true: 스와이프 하면 첫 번째 액션이 즉시 실행 false: 스와이프 된 상태에서 나타는 버튼을 눌러서 액션 실행 실제 적용 코드 (이슈 트래킹 앱) func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let deleteAction = makeDeleteAction() let closeAction = makeCloseAction() let configuration = UISwipeActionsConfiguration(actions: [deleteAction, closeAction]) configuration.performsFirstActionWithFullSwipe = false return configuration } private func makeDeleteAction() -> UIContextualAction { let deleteAction = UIContextualAction(style: .destructive, title: nil) { (action, view, completionHandler) in // TODO: 얼럿 띄우고 삭제 로직 completionHandler(true) } deleteAction.image = UIImage(systemName: "trash") return deleteAction } private func makeCloseAction() -> UIContextualAction { let closeAction = UIContextualAction(style: .normal, title: nil) { (action, view, completionHandler) in // TODO: 이슈 닫기 로직 completionHandler(true) } closeAction.image = UIImage(systemName: "archivebox.fill") closeAction.backgroundColor = .systemIndigo return closeAction }

September 20, 2024

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