coo*_*nie 6 uitableview ios swift
我在UITableViewCell中有一个操作按钮,我想检测按钮的按下时间以及ViewController中按下的单元格编号,以便在ViewController.swift中创建音频播放列表.
我已经陷入这个问题一段时间了,我真的很赞赏你的建议.这是代码.
ViewController.swift
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UINib(nibName: "Cell", bundle: nil), forCellReuseIdentifier: "cell")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! Cell
return cell
}
}
Run Code Online (Sandbox Code Playgroud)
Cell.swift
import UIKit
class Cell: UITableViewCell {
@IBOutlet weak var button: UIButton!
@IBAction func buttonPressed(_ sender: Any) {
***[Code to send the pressed cell's number to ViewController]***
}
}
Run Code Online (Sandbox Code Playgroud)
Pul*_*sar 10
你可以选择一个老式的代表模式.这样做的好处是不会将视图控制器与单元格耦合.不要忘记让你的代表weak避免保留周期.
您可以从表视图中找到单元索引路径.(我假设按单元格编号表示索引路径)
protocol CellDelegate: class {
func didTap(_ cell: Cell)
}
class Cell: UITableViewCell {
weak var delegate: CellDelegate?
@IBAction func buttonPressed(_ sender: Any) {
delegate?.didTap(self)
}
}
class ViewController: UIViewController, CellDelegate {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = ...
cell.delegate = self
return cell
}
func didTap(_ cell: Cell) {
let indexPath = self.tableView.indexPath(for: cell)
// do something with the index path
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1872 次 |
| 最近记录: |