iOS/개념 & 개발

[iOS/Swift] 선택한 TableViewCell의 IndexPath 구하기

유정주 2021. 12. 13. 00:10
반응형

[iOS/Swift] 선택한 TableViewCell의 IndexPath 구하기

안녕하세요. 개발하는 정주입니다.

 

오늘은 선택한 TableViewCell의 IndexPath 구하는 방법에 대해 포스팅하려고 합니다.

바로 시작합니다.

 


구현 상황

스토리보드에서 segue를 이용해 화면 이동을 했습니다.

TableViewCell을 누르면 다음 화면으로 데이터를 넘기며 넘어가는 로직입니다.

따라서 cell을 눌렀을 때 누른 cell의 indexPath를 구해야 했습니다.

 


indexPathForSelectedRow

https://developer.apple.com/documentation/uikit/uitableview/1615000-indexpathforselectedrow

 

Apple Developer Documentation

 

developer.apple.com

모든 답은 공식 문서에 있었습니다.

선택한 cell의 IndexPath를 return 해주는 Property가 있습니다.

 

공식 문서는 해당 프로퍼티를

"An index path that identifies the row and section of the selected row."라고 설명합니다.

선택한 cell의 index path가 필요했던 지금 상황에 딱 맞는 property입니다.

 

해당 프로퍼티를 사용할 때의 주의점은 다중 선택을 한 상황입니다.

If there are multiple selections, this property contains the first index-path object in the array of row selections.

여러 개의 selection이 있다면 첫 번째 index path만 준다고 합니다.

저의 상황은 아니지만 혹시 포스팅을 보고 사용을 생각하시는 분이라면 주의해 주세요.

 

https://developer.apple.com/documentation/uikit/uitableview/1614864-indexpathsforselectedrows

 

Apple Developer Documentation

 

developer.apple.com

이런 상황이라면 Index Path 배열을 얻을 수 있는 프로퍼티를 사용해 주세요.

 


사용 예시

if let selectedIndexPath = countryTableView.indexPathForSelectedRow {
    nextViewController.country = countries[selectedIndexPath.row]
}

index path를 옵셔널 바인딩하여 배열에서 값을 가져옵니다.

이로서 제가 원하는 기능을 구현했습니다!


참조

https://developer.apple.com/documentation/uikit/uitableview/1614864-indexpathsforselectedrows

 


아직은 초보 개발자입니다.

더 효율적인 코드 훈수 환영합니다!

공감 댓글 부탁드립니다.

 

 

 

반응형