之前做过单选多选题的处理,现在把当时遇到的问题和解决方案记录下来:

刚开始的时候,定义 var selectedIds = [String]()  //存储选中的id

// if self.questionnaire?.type == "radio" {
// selectedIds = []
// selectedIds.append((self.questionnaire?.offeredAnswers[indexPath.row]["id"])!)
// print("单选selectedIds",selectedIds)
// } else if self.questionnaire?.type == "checkbox" {
// self.tableView.allowsMultipleSelection = true //允许多选.
// selectedIds.append((self.questionnaire?.offeredAnswers[indexPath.row]["id"])!)
// print("多选选中selectedIds",selectedIds)
// //取消选中,移除当前取消项数据.

// }

但对tableview 可以多选的时候,每选一次把选项的id append进去之后,当取消选中的时候,是不知道怎么处理,移除当前取消项的id.

主要的思路是:多选先判断是否包含ID,有则移除,没有则添加!

记得当时还用上了这个方法:

// func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
// let section = indexPath.section
// if section == 1 {
// print("index******************",indexPath.row)
// selectedIds.removeAtIndex(indexPath.row)
// print("取消选中selectedIds",selectedIds)
// }
// }

但它会出现问题: 点击几次选中取消后,会出现out of range的错误.

以上是用了系统的方法.

 

后来改成了一下的方式:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
  tableView.deselectRowAtIndexPath(indexPath, animated: false) //必须加上这个.
  let section = indexPath.section
  if section == 0 {
    return
  } else if section == 1 {
    let optionAction = self.questionnaire?.offeredAnswers[indexPath.row]
    let id = optionAction!["id"]
    if isSingleSelecte {
      selectedIds.removeAll()
      selectedIds.append(id!)
    } else {
      if selectedIds.contains(id!){
        selectedIds.removeAtIndex(selectedIds.indexOf(id!)!)
      } else {
      selectedIds.append(id!)
    }
  }
  print(selectedIds)
  tableView.reloadData()

}

var isSingleSelecte: Bool{
  return questionnaire == nil ? false : questionnaire!.type == "radio"
}

选项选中时,cell的底色和文字颜色都要改变,一开始我是在cellForRowAtIndexPath这个方法里面写上了:

// mQuestionnaireOptionCell?.selectedBackgroundView = UIView()
// mQuestionnaireOptionCell?.selectedBackgroundView?.backgroundColor = UIColor(red: 33/255, green: 150/255, blue: 243/255, alpha: 1)
// mQuestionnaireOptionCell?.questionnaireOption?.highlightedTextColor = UIColor.whiteColor()

而后改成如下写法:

var cell: UITableViewCell?

cell = tableView.dequeueReusableCellWithIdentifier("Questionnaire", forIndexPath: indexPath)
let mQuestionnaireCell = cell as? QuestionnaireOptionCell

let id = optionAction!["id"]
if selectedIds.contains(id!){
  mQuestionnaireOptionCell?.backgroundColor = UIColor(red: 33/255, green: 150/255, blue: 243/255, alpha: 1)
  mQuestionnaireCell?.questionnaireOption.textColor = UIColor.whiteColor()
} else {
  mQuestionnaireOptionCell?.backgroundColor = UIColor.whiteColor()
  mQuestionnaireCell?.questionnaireOption.textColor = UIColor.blackColor()
}

另外,tableView.userInteractionEnabled = false写上这代码,整个tableview都不可点了.