我在 View Controller 中有一个 TableView ,它通过 segue 连接到 3 个不同的 View Controller 。每个都有一个标识符。
为了对相应的 View Controller 执行转场,我创建了一个数组,其中包含每个转场的标识符。像这样:
var tableauSegues = ["versChapitre1", "versChapitre2", "versChapitre3"]
为了根据数组的索引管理 segue,我选择在 iB 操作中使用 for in 循环,如下所示:
@IBAction func versHistoire(_ sender: UIButton) {
for i in tableauSegues {
performSegue(withIdentifier: i, sender: self)
}
}
问题是所有 3 个转场都被执行了。我只想一次执行一个 segue。
有什么想法吗?
最佳答案
显然,您想避免循环,而只想使用 tableauSegues[row]
。但诀窍在于如何获取 行
。
最重要的是,您应该让单元格处理单元格的点击,并让单元格在其按钮被点击时通知 TableView Controller 。但诀窍在于,当它这样做时,它应该在这样做时提供对自身的引用,以便 View Controller 可以确定哪一行的按钮被点击了。
因此,直接在按钮和 View Controller 之间删除现有的 @IBAction
,而是将其连接到单元基类中的 @IBAction
。
// CustomCell.swift
import UIKit
protocol CustomCellDelegate: class {
func didTapButton(_ sender: Any, in cell: CustomCell)
}
class CustomCell: UITableViewCell {
@IBOutlet weak var customLabel: UILabel!
static let preferredReuseIdentifier = "CustomCell"
weak var delegate: CustomCellDelegate?
func configure(text: String, delegate: CustomCellDelegate) {
customLabel.text = text
self.delegate = delegate
}
@IBAction func didTapButton(_ sender: Any) {
delegate?.didTapButton(sender, in: self)
}
}
请注意,当我配置该单元格时,我将让 TableView 不仅提供需要在单元格中显示的任何值,而且还指示它是该单元格的委托(delegate):
// ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var tableauSegues = ["versChapitre1", "versChapitre2", "versChapitre3"]
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableauSegues.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CustomCell.preferredReuseIdentifier, for: indexPath) as! CustomCell
cell.configure(text: "...", delegate: self)
return cell
}
}
extension ViewController: CustomCellDelegate {
func didTapButton(_ sender: Any, in cell: CustomCell) {
let row = tableView.indexPath(for: cell)!.row
let identifier = tableauSegues[row]
performSegue(withIdentifier: identifier, sender: self)
}
}
关于ios - 如何确保我的 for in 循环使我只能执行一个 segue?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55315084/