다양한 섹션에서 각 셀의 모든 선택된 상태를 유지하는 뷰 컨트롤러의 데이터 모델을 유지 보수하는 것이 좋습니다. (셀 항목을 설명하는 더 많은 이름을 선택하십시오).
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)
}
}
희망이 맞는 것!
의미가 있습니다. 그래서 xcode는이 줄을 좋아하지 않습니다 : dataModel [indexPath.section] = dataModel [indexPath.section] .map ({$ 0.isSelected = false}) –
또한 치명적인 오류가 발생했습니다 : if dataModel [indexPath.section] [indexPath.row] .isSelected { –
죄송합니다. 직접 코드를 실행하지 않았습니다! 하위 배열의 각 요소를 통과하는 for 루프로 맵을 대체하고 선택을 취소했는지 확인하십시오. 범위를 벗어나는 인덱스의 경우 tableView : numberOfRowsInSection과 마찬가지로 올바른 섹션 수를 반환하려면 tableView : numberOfSectionsInTableView를 구현해야합니다. 둘 다 dataModel의 .count 속성을 기반으로하는 값을 반환해야합니다. 범위를 벗어난 인덱스를 가져 오지 말아야합니다. – Undrea