0

我有一個tableView與人員列表。我想選擇多個單元格。我創建了一個字典來存儲選定的單元格(screenshot)。didSelectRowAtIndexPath中的tableViewCell配件類型問題

var checkedSubjects: [Person: Bool] = [Person: Bool]() 

後來,當我選擇一個單元格則顯示單元附近的對勾,並保存在我的數組(screenshot)。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    var cell: SearchTableViewCell = tableView.dequeueReusableCellWithIdentifier("CELL", forIndexPath: indexPath) as! SearchTableViewCell 
    cell.tintColor = UIColor(hex: 0x3f51b5) 
    cell.subjectNameLabel.text = subjects[indexPath.row].name 
    cell.subjectDescriptionLabel.text = "(\(subjects[indexPath.row].type))" 

    let person = Person(id: subjects[indexPath.row].id, name: subjects[indexPath.row].name, type: subjects[indexPath.row].type) 
    if checkedSubjects[person] != nil { 
     cell.accessoryType = checkedSubjects[person]! ? .Checkmark : .None 
    } 
    return cell 
} 

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    tableView.deselectRowAtIndexPath(indexPath, animated: false) 
    let index = indexPath.row 
    let person = Person(id: subjects[index].id, name: subjects[index].name, type: subjects[index].type) 
    if tableView.cellForRowAtIndexPath(indexPath)!.accessoryType == .Checkmark { 
     tableView.cellForRowAtIndexPath(indexPath)!.accessoryType = .None 
     checkedSubjects[person] = false 
     counter-- 
    } else { 
     tableView.cellForRowAtIndexPath(indexPath)!.accessoryType = .Checkmark 
     checkedSubjects[person] = true 
     counter++ 
    } 
    if counter > 0 { 
     saveBtn.enabled = true 
     let text = counter == 1 ? "Add \(counter) person" : "Add \(counter) persons" 
     saveBtn.setTitle(text, forState: UIControlState.Normal) 
    } else { 
     saveBtn.enabled = false 
     saveBtn.setTitle("Choose persons", forState: UIControlState.Normal) 
    } 
} 

但是,當我按下這個小區中的一個更多的時間,我希望它恢復到默認視圖。它刪除複選標記,但文本不佔用空白區域(screenshot)。標籤的尾部限制設置爲容器邊距。

我試過的tableView的reloadData()在didSelectRowAtIndexPath方法,但它並沒有幫助。

任何想法,我可以解決這個問題?

+0

@馬特謝謝你,我也跟着你的答案,現在它工作得很好!) – mikle94

+0

請張貼此作爲一個答案,將其標記爲accpeted進行適當的家政服務。 –

+0

@matt它幫助了我,所以讓它成爲)。 – mikle94

回答

1

我覺得這裏的問題是,你試圖操縱物理電池在didSelectRow實現。這是關於事情的錯誤方式。請勿嘗試更改或甚至讀取didSelectRow實現中的單元的附件類型!相反,操作起來完全依靠模型(checkedSubjects)和重裝受影響的行,所以該視圖拿起改變模型(因爲cellForRow將被調用)。