【发布时间】:2026-01-22 20:40:01
【问题描述】:
我使用带有两个部分的UITableView,我使用一个名为sections 的数组作为部分标题标题,一个名为sectionItems 的数组包含两个字符串值数组来填充这些部分。
let sections = ["Section 1", "Section 2"]
var sectionItems = [ ["One","Two", "Three", "Four"], ["Another One"] ]
UITableView 可以很好地显示数据,但是当用户选择表格视图单元格时,我试图继续。问题是我对两个不同的部分有两个不同的 segue。
如何将每个 segue 用于适当的部分?
这就是我正在尝试的,
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
tableView.deselectRowAtIndexPath(indexPath, animated: true)
//Optional error occurs here for section property
let section = self.tableView.indexPathForSelectedRow!.section
if section == 0 {
self.performSegueWithIdentifier("sectionOneSegue", sender: cell)
} else if section == 1 {
self.performSegueWithIdentifier("sectionTwoSegue", sender: cell)
}
}
但是,在声明属性部分时,这给了我一个可选错误。
此外,当启动 segue 时,我试图将相关数据传递给细节控制器。
这里我试图确保在 sectionItems 数组中我使用数组中的第一个数组,方法是使用节号,然后是所选单元格行的确切字符串值。
if segue.identifier == "sectionOneSegu" {
let navController = segue.destinationViewController as! UINavigationController
let detailController = navController.topViewController as! DetailViewController
var row = self.tableView.indexPathForSelectedRow!.row
detailController.upcomingType = sectionItems[1][row]
detailController.mode = 1
}
我不确定这是否正确。有人可以帮助我了解为什么在选择单元格行时会发生错误以及如何修复它以使用正确的 segue 吗?以及如何传递相关数据?
【问题讨论】:
-
获取章节号,你可以使用:
indexPath.section。 -
您可以将 segues 链接到原型单元格,然后当您触摸一个单元格时,它将调用您的 prepareForSegue 方法,您可以在其中检查 segue.identifier 属性。从那里您将像现在一样提取选定的行并从表数据中获取数据。看起来所选行的索引路径为零,这就是您无法提取部分值的原因。在您当前的示例中,这无关紧要,因为您将 indexPath 作为参数。我不知道苹果何时更新要选择的单元格的状态,但有可能直到 didSelectRow 之后
-
仅供参考,您永远不应该从 cellForRowAtIndexPath 外部调用 dequeueReusableCellWithIdentifier
标签: ios arrays swift uitableview