0

我想找出所有 UITableViewCells(数量不同),其中有一个 detailTextLabel,其中包含文本“完成”。我怎样才能在 Swift 中做到这一点?

4

1 回答 1

0

你不应该这样做。无论是 Swift 还是任何其他语言。您应该查询数据源,因为那是存储真实状态的地方。如果您将单元格滚动到屏幕外,它会被重复使用,并且文本会被设置为其他内容。你不能依赖这些信息。更糟糕的是,如果您依赖单元格中的文本,您将永远无法全面了解数据源,因为屏幕外的单元格根本不存在。

以下是您应该做的:在代码中的某处,您"Done"根据对象的状态设置文本。使用相同的决定来查找所有已完成的对象。

例如,如果你的对象有一个isDonegetter,你希望使用这样的东西来创建单元格:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("ProjectCell", forIndexPath: indexPath) as ProjectCell

    let project = allProjects[indexPath.row]
    if project.isDone {
        cell.detailTextLabel?.text = "Done"
    }
    else {
        cell.detailTextLabel?.text = nil
    }
    return cell
}

如您所见,您决定取决于isDone是否"Done"显示文本。

因此,您可以创建一个使用相同测试的函数来创建一个仅包含已完成项目的数组。

func projectsThatAreDone(allProjects: [Project]) -> [Project] {
    let matchingProjects = allProjects.filter {
        return $0.isDone
    }
    return matchingProjects
}

然后你使用let doneProjects = projectsThatAreDone(allProjects)

于 2014-11-28T15:45:30.817 回答