在 Swift 中以编程方式在 TableViewCell 上执行根视图控制器 Segue



下面的代码创建一个tableviewcell并在其中放置一个对象。用于将数据放置在表视图单元格中的代码不存在。我想做的只是当用户单击表视图单元格时,将其转移到基本视图控制器类。无需展示如何回去。

var itemName : [NSManagedObject] = []
var theField = UITableView()
override func viewDidLoad() {
super.viewDidLoad()

theField.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let title = itemName[indexPath.row]
let cell = theField.dequeueReusableCell(withIdentifier: "MyCell", for : indexPath)
cell.selectionStyle = .default
let attr1 = title.value(forKey: "name") as? String

let text = [attr1].flatMap { $0 }.reduce("", +)
cell.textLabel?.text = "(text)"
cell.textLabel?.textAlignment = .center
cell.layoutMargins = UIEdgeInsets.zero


cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = UIEdgeInsets.zero
cell.layoutMargins = UIEdgeInsets.zero

return cell
}
@objc func moveRight() {
//pass tableview cell
let vce = fullScreen()
vce.text = UITableViewCell


vce.modalPresentationStyle = .overCurrentContext // actually .fullScreen would be better
vce.present(vce, animated: true)}

假设你有一个数组titles

cell.textLabel?.text = titles[indexPath.row]

,然后在此方法中执行操作:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
moveRight(titles[indexPath.row])
}
func moveRight(_ title:String) {
//pass tableview cell
let vc = fullScreen()
vc.text = title
self.navigationController!.pushViewController(vc, animated: true)        
}

您需要实现UITableViewDelegate协议。所以:

extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { .. }
}

最新更新