获取uitableview的多个选定行信息

Get multiple selected rows info of an uitableview

到目前为止,我有一个可以处理多个 selection 行的 tableView。一切工作正常,除非我试图获取我 selected 的行数组。

这是我的 Stat.swift class:

class Stat: Equatable {
      var statName: String = ""
      var statCalendar: String = ""
      var statEvents : [StatEvents] = []
}

struct StatEvents {
    var isSelected: Bool = false
    var name: String
    var dateRanges: [String]
    var hours: Int
}
func == (lhs: Stat, rhs: Stat) -> Bool {
     return (lhs.statEvents == rhs.statEvents)
}

这是我的 EventsViewController.swift class:

var currentStat = Stat()
var selectedMarks = [StatEvents]()

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell

    cell.textLabel?.font = UIFont.systemFontOfSize(8.0)
    cell.textLabel?.text = "\(currentStat.statEvents[indexPath.row].name)  \(currentStat.statEvents[indexPath.row].dateRanges) horas=\(currentStat.statEvents[indexPath.row].hours)"

    if currentStat.statEvents[indexPath.row].isSelected{
        cell.accessoryType = .Checkmark

    } else {
        cell.accessoryType = .None
    }
    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.deselectRowAtIndexPath(indexPath, animated: false)
    currentStat.statEvents[indexPath.row].isSelected = !currentStat.statEvents[indexPath.row].isSelected

    if (contains(selectedMarks, currentStat.statEvents[indexPath.row])) {
        //To-Do: remove the object in selectedMarks
    } else {
        selectedMarks.append(currentStat.statEvents[indexPath.row]) //add the object to selectedMarks
    }

    tableView.reloadData()
}

问题出在 "didSelectRowAtIndexPath" 方法中。当我 select 任何行时,它将对象附加到 "selectedMarks" 数组中(这工作正常),但问题是当我 deselect 其中一些行时,它应该擦除回来selectedMarks 数组中的对象。我正在尝试使用 "contains" 方法,但在该行

中出现编译错误

could not find an overload for contains that accepts the supplied arguments

我通过在 Stat class 中添加 Equatable 协议更新了我的问题,但我再次遇到同样的错误:

could not find an overload for contains that accepts the supplied arguments

并且还收到一个新错误:

Command failed due to signal: Segmentation fault: 11

为了让 contains 方法在 Swift 2 中完成它的工作,你的 StatEvents 结构应该符合 Equatable 协议,如下例所示:

struct StatEvents: Equatable
{
    // ...  
    // implementation of your structure....
    // ...
}    

// Needed for conforming to the Equatable protocol

func == (lhs: StatEvents, rhs: StatEvents) -> Bool
{
    // Return true if the parameters are equal to each other
}

此外,Swift2中没有全局contains函数,所以你需要调用新的数组扩展方法contains,你的情况是这样的:

selectedMarks.contains(currentStat.statEvents[indexPath.row])

同时将协议声明添加到 StatEvents 结构中,而不是添加到 Stat class 中。您对 == 方法的实现也不正确。如上所示,它应该检查 StatEvents 类型的两个对象之间的相等性。