我想知道存储对 UITableViewCell
在其中表示的模型的引用是否“正确”。
我问的原因是因为在其中的按钮中发生点击操作时需要了解模型。
是否有更好的(又名:理想的)方法来做到这一点?
例子:
class Person {
var name: String
var lastName: String
var age: Int
}
protocol PersonCellDelegate: NSObjectProtocol {
// should the second parameter be the model that the cell represents?
func songCell(_ cell: PersonCell, didClickAtEditButtonOfPerson person: Person)
}
class PersonCell: UITableViewCell {
@IBOutlet private weak var nameLabel: UILabel!
@IBOutlet private weak var lastNameLabel: UILabel!
@IBOutlet private weak var ageLabel: UILabel!
@IBOutlet private weak var editButton: UIButton!
// does the cell need to store its reference?
var person: Person! {
didSet {
nameLabel.text = person.name
// ...
}
}
weak var delegate: PersonCellDelegate?
// ...
}
最佳答案
表格 View 单元格是一个 View 。它对应用程序逻辑了解得越少越好。
您可以使用 indexPath(for:)
方法检索使用的实体:
protocol MyTableViewCellDelegate: AnyObject {
func myTableViewCellDidSomething(_ cell: MyTableViewCell)
}
class MyTableViewCell: UITableViewCell {
weak var delegate: MyTableViewCellDelegate?
}
class ViewController: UITableViewController, MyTableViewCellDelegate {
var personList: [Person] = []
func myTableViewCellDidSomething(_ cell: MyTableViewCell) {
guard let indexPath = tableView.indexPath(for: cell) else { return }
let person = personList[indexPath.row]
// ...
}
}
关于ios - 将模型对象的引用存储在其中表示的 UITableViewCell 中是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55284798/