UIStoryboardSegue
是 iOS 开发中用于在不同视图控制器之间进行导航的一种机制。它定义了从一个视图控制器到另一个视图控制器的过渡方式。UITableView
是 iOS 中用于显示列表数据的常用控件。
UITableView
中点击某个单元格时,跳转到详细页面。要在仅当条件为真时才从 UITableView
执行 UIStoryboardSegue
,可以在 UITableView
的 didSelectRowAt
方法中进行条件判断,并根据条件决定是否执行 segue。
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
// MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10 // 假设有10行数据
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "Row \(indexPath.row)"
return cell
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// 假设我们有一个条件,只有当 indexPath.row 是偶数时才执行 segue
if indexPath.row % 2 == 0 {
performSegue(withIdentifier: "DetailSegue", sender: self)
} else {
// 条件不满足时的处理,例如显示一个提示
let alert = UIAlertController(title: "条件不满足", message: "仅偶数行可以跳转", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
// MARK: - UIStoryboardSegue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "DetailSegue" {
if let detailVC = segue.destination as? DetailViewController {
// 可以在这里传递数据
detailVC.data = "Row \(tableView.indexPathForSelectedRow!.row)"
}
}
}
}
原因:可能是 segue 的 identifier 设置错误,或者 performSegue
方法未被正确调用。
解决方法:
performSegue
方法在正确的条件下被调用。原因:在 prepare(for:sender:)
方法中未正确设置目标视图控制器的数据。
解决方法:
prepare(for:sender:)
方法中正确设置了目标视图控制器的数据属性。通过上述方法,可以有效地控制 UITableView
中的 segue 执行,并确保在满足特定条件时才进行导航。
领取专属 10元无门槛券
手把手带您无忧上云