Tableview自定义单元格将数据传递到下一页

时间:2018-12-27 13:26:08

标签: swift uitableview cell

我已经尝试了几天,以将自定义单元格按钮设置为表格视图单元格。我想按下按钮“ AddItem”,并将我按下的那一行的数据传递给标签,然后将数据传递给下一个屏幕。我已经在堆栈视图中查看了多个类似于我的问题的解决方案,但仍然无法使我的工作正常。有人能帮我一下吗?该应用的屏幕截图如下。

这是我的代码:

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

    let item = ["Apple","Orange"]
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return item.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = item[indexPath.row]
        return cell
    }


    @IBOutlet var tblView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()

    }

}

first page

second page

1 个答案:

答案 0 :(得分:0)

将滑行板标识符添加到NexVC

enter image description here

然后

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

     let vc = self.storyboard!.instantiateViewController(withIdentifier: "NextVC") as! NextVC
     vc.loadViewIfNeeded()
     vc.lbl.text = item[indexPath.row]
     self.navigationController?.pushViewController(vc, animated: true)

}

cellForRowAt

    cell.button.tag = indexPath.row

    cell.button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)

    return cell
}

@objc func buttonTapped (_ sender:UIButton) {

    print(item[sender.tag])
}