[英]How to get the cell object in tableView:(UITableView *)tableView heightForRowAtIndexPath function?
[英]How to get tableView instance from Custom UITableview cell?
我有一個帶有自定義UITableViewCell的tableView,並且在該單元格類中,我想訪問保存它的tableView。 為此,我使用的是cell.superView,它返回nil。 但是當我不使用任何自定義UITableViewCell時,同樣可以正常工作。
這是我的代碼,
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? TestTableViewCell
cell?.textLabel?.text = "Test"
return cell!
}
class TestTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
}
func loadDetails() {
let tableView = self.superview //which is returning nil here
}}
在UITableViewDelegate
,點擊一個單元格時,您可以知道哪個UITableView
擁有它。
觸發的方法是:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// tableView is the UITableView holding the cell.
}
正如其他人在評論中告訴您的那樣,單元格可以訪問tableView的屬性不是一個好主意,因為該單元格依賴於表。 這意味着,如果您向單元格授予權力以能夠更改tableView中的屬性,則兩者都是依賴的,並且數百個更改表中屬性的單元格可能會很混亂。 因此,重新考慮設計(即面向協議的編程)是一個好主意。
但是,如果沒有其他可行的方法,則可以添加一個private weak var
(我們需要將其私有以確保只有單元格可以訪問它,而弱的原因是我們不希望有保留周期):
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! TestTableViewCell
cell.tableView = tableView
cell.textLabel?.text = "Test"
return cell
}
class TestTableViewCell: UITableViewCell {
private weak var tableView: UITableView?
override func awakeFromNib() {
super.awakeFromNib()
}
func loadDetails() {
guard let tableView = tableView else { return }
// Here you can access your tableView
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.