【发布时间】:2020-01-20 11:57:57
【问题描述】:
我正在使用自定义 tableView 单元格,它在 VC1 中有一个按钮和一些标签。我想要做的是当我连续单击按钮时,然后打开 VC2 并将当前标签的文本(名称 [i])发送到 VC2。
但就我而言,我坚持如何在 pressButton func 中传递 buttonTag 以准备 func controller.playingSong = names[buttonTag]。我尝试使用全局变量,然后每次 prepare() 检索该变量,但它没有工作属性,似乎 prepare() 将在 pressButton() 方法之前执行。
好吧,我确实搜索了很多但没有找到解决方案,我可以将prepare() 结合到我的pressButton() 中,换句话说,使用segue 时是否需要prepare?
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myTableView: UITableView!
let REUSE_ID = "CustomCell"
var names = ["first", "second", "third"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func pressButton(_ sender: UIButton) {
let buttonTag = sender.tag
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: REUSE_ID, for: indexPath) as! CustomCell
cell.myButton.tag = indexPath.row
cell.songName.text = names[indexPath.row]
// cell.myButton.addTarget(self, action: #selector(self.pressButton(_:)), for: .touchUpInside)
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case "playingSongs":
let controller = segue.destination as! OpenedVC
controller.playingSong = names[buttonTag]
default: break
}
}
}
【问题讨论】:
标签: swift button tableview segue