【发布时间】:2016-11-20 04:09:41
【问题描述】:
我正在尝试使用以下代码以编程方式选择我的 tableview 中的所有行:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:myTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! myTableViewCell
cell.accessoryType = .None
if allJobsSelected {
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor(red: 250/255, green: 182/255, blue: 17/255, alpha: 1)
cell.contentView.backgroundColor = UIColor(red: 250/255, green: 182/255, blue: 17/255, alpha: 1)
cell.selectedBackgroundView = bgColorView
cell.accessoryType = .Checkmark
cell.highlighted = false
cell.selected = true
// cell.accessoryType = .Checkmark
self.tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.None)
self.tableView(self.tableView, didSelectRowAtIndexPath: indexPath)
}
var job: Jobs!
job = jobs[UInt(indexPath.row)] as! Jobs
cell.reports2JobTitle.text = job.jobTitle
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.allowsMultipleSelection = true
if let cell:myTableViewCell = tableView.cellForRowAtIndexPath(indexPath) as? myTableViewCell {
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor(red: 250/255, green: 182/255, blue: 17/255, alpha: 1)
cell.contentView.backgroundColor = UIColor(red: 250/255, green: 182/255, blue: 17/255, alpha: 1)
cell.selectedBackgroundView = bgColorView
cell.accessoryType = .Checkmark
cell.highlighted = false
self.tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.Bottom)
}
}
我的问题是,当我转到下一个视图控制器时,只有已出队的行才会添加到我的表的数据模型中。为了将所有行添加到我的表的数据模型中,我必须手动滚动整个表。如何更改此设置,以便将所有选定的行添加到我的表的数据模型中,而无需滚动整个表?
我无法理解的是,在选择了所有行之后,我会按如下方式遍历我的 indexPaths,但除非我首先滚动整个表格,否则不会添加所有 indexPaths。
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "reportsDisplay") {
let controller = segue.destinationViewController as! ReportsDisplayViewController
var selectedJob : Jobs!
if let indexPaths = tableView.indexPathsForSelectedRows {
for i in 0 ..< indexPaths.count {
let thisPath = indexPaths[i]
selectedJob = jobs[UInt(thisPath.row)] as! Jobs
let jobTitle = selectedJob.jobTitle
let id = selectedJob.identifier
jobsToReport.append(jobTitle)
jobsID.append(id)
}
}
controller.reportedJobs = jobsToReport
controller.idOfJobs = jobsID
}
}
【问题讨论】:
-
我的模型中只有字符串数据。我想我可以通过使用一组元组的解决方法来实现这一点,即职位和一个布尔值来指示是否选择了该特定职位。我只是觉得必须有更优雅的方式来实现这一点。
-
永远不会自己调用包含
will、should和did的委托方法。它们由框架专门调用。 (一个罕见的例外是 KVO 的will/didChangeValueForKey:)
标签: ios swift uitableview didselectrowatindexpath