2016-07-29 2 views
0

UITableView에 여러 섹션이 있으며 각 섹션의 숫자는 UITableViewCells입니다.NSIndexPath를 사용하여 선택한 셀을 어떻게 추적합니까?

각 섹션에 대해 선택된 셀을 추적하고 선택한 셀에 대한 이미지를 표시하고 싶습니다. 선택 된 셀의 이미지를 표시 한 후

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    someArray.append(indexPath) 
} 

과 : 그래서 배열에 저장에 대해 생각했다

for indices in self.someArray { 
    if indices == indexPath { 
     cell.button.setImage(UIImage(named: "selected"), forState: UIControlState.Normal) 
    } else { 
     cell.button.setImage(UIImage(named: "unselected"), forState: UIControlState.Normal) 
    } 
} 

나는 또한 그것을 그렇게하고 싶습니다 한 번에 섹션 당 하나의 셀만 선택할 수 있으며 각 섹션마다 각 셀렉션이 유지된다는 점입니다.

선택 사항을 그대로 두지 마십시오. 일부 행에 대해 섹션 0에서 선택을 할 때마다 내 다른 섹션에도 동일한 행 인덱스가 선택됩니다.

어떻게 수정합니까?

답변

3

다양한 섹션에서 각 셀의 모든 선택된 상태를 유지하는 뷰 컨트롤러의 데이터 모델을 유지 보수하는 것이 좋습니다. (셀 항목을 설명하는 더 많은 이름을 선택하십시오).

var dataModel: [[Element]] // First array level is per section, and second array level is all the elements in a section (e.g. dataModel[0][4] is the fifth element in the first section) 

이 배열은 가능성에 isSelected 당신이 선택 해제 모든 행으로 시작 추정, 거짓 요소의 무리로 초기화 될 것이다 :

struct Element { 
    var isSelected: Bool // selection state 
} 

그런 다음 뷰 컨트롤러는 그래서 데이터 모델을 할 것입니다.

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    // Check if there are any other cells selected... if so, mark them as deselected in favour of this newly-selected cell 
    dataModel[indexPath.section] = dataModel[indexPath.section].map({$0.isSelected = false}) // Go through each element and make sure that isSelected is false 

    // Now set the currently selected row for this section to be selected 
    dataModel[indexPath.section][indexPath.row].isSelected = true 
    } 

(. 더 효율적인 방법 대신 전체 부분 배열을 매핑의 거짓을 각 섹션에 대해 마지막으로 선택된 행을 유지하고 표시 할 수 있습니다)

:

이제 tableView:didSelectRowAtIndexPath 기능은 다음과 같을 것

이제 tableView : cellForRowAtIndexPath에서 dataModel을 기반으로 셀을 선택했는지 여부를 표시해야합니다. 데이터 모델에서 선택한 상태를 유지 관리하지 않으면 셀이 화면에서 스크롤되는 즉시 선택 상태가 사라집니다. 또한 dequeueReusableCellWithIdentifier은 셀을 제대로 새로 고치지 않으면 선택한 상태를 반영하는 셀을 다시 사용합니다.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("yourCellIdentifier") as! YourCellType 

    // If your data model says this cell should be selected, show the selected image 
    if dataModel[indexPath.section][indexPath.row].isSelected { 
     cell.button.setImage(UIImage(named: "selected"), forState: UIControlState.Normal) 
    } else { 
     cell.button.setImage(UIImage(named: "unselected"), forState: UIControlState.Normal) 
    } 
    } 

희망이 맞는 것!

+0

의미가 있습니다. 그래서 xcode는이 줄을 좋아하지 않습니다 : dataModel [indexPath.section] = dataModel [indexPath.section] .map ({$ 0.isSelected = false}) –

+0

또한 치명적인 오류가 발생했습니다 : if dataModel [indexPath.section] [indexPath.row] .isSelected { –

+0

죄송합니다. 직접 코드를 실행하지 않았습니다! 하위 배열의 각 요소를 통과하는 for 루프로 맵을 대체하고 선택을 취소했는지 확인하십시오. 범위를 벗어나는 인덱스의 경우 tableView : numberOfRowsInSection과 마찬가지로 올바른 섹션 수를 반환하려면 tableView : numberOfSectionsInTableView를 구현해야합니다. 둘 다 dataModel의 .count 속성을 기반으로하는 값을 반환해야합니다. 범위를 벗어난 인덱스를 가져 오지 말아야합니다. – Undrea

관련 문제