我想创建一个cell
变量并分配dequeueReusableCell
以避免重复代码。我不知道我该怎么做。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell : UITableViewCell!
if let url = media.url {
if Helper.isImageType(url: url)
{
cell = tableView.dequeueReusableCell(withIdentifier: newsFeedImageTableViewViewCellId, for: indexPath) as! NewsFeedImageTableViewViewCell
cell.imageTappedDelegate = self
}else
{
cell = tableView.dequeueReusableCell(withIdentifier: newsFeedVideoTableViewViewCellId, for: indexPath) as! NewsFeedVideoTableViewViewCell
cell.videoTappedDelegate = self
}
cell.linkTappedDelegate = self
cell.backgroundColor = UIColor(rgb: 0xF2F2F2)
cell.isAccessibilityElement = true
cell.selectionStyle = .none
tableViewIndex = indexPath
if let _states = states?[indexPath.section]{
cell.state = _states[indexPath.row]
}
return cell
}
return UITableViewCell()
}
如果你看到我的代码,它只是不同
let cell = tableView.dequeueReusableCell(withIdentifier: newsFeedVideoTableViewViewCellId, for: indexPath) as! NewsFeedImageTableViewViewCell
和
let cell = tableView.dequeueReusableCell(withIdentifier: newsFeedVideoTableViewViewCellId, for: indexPath) as! NewsFeedVideoTableViewViewCell
其他代码行相同。
我正在尝试声明变量 this 但它不起作用:
let cell: UITableViewCell!
“UITableViewCell”类型的值没有成员“imageTappedDelegate”
更新:- 添加了单元类定义:
class NewsFeedTableViewViewCell : BaseTableViewCell{
var statisticsSlidingCellId = "statisticsSlidingCellId"
var linkTappedDelegate : LinkTappedDelegate!
var state : State?{
didSet{
}
}
}
class NewsFeedImageTableViewViewCell: NewsFeedTableViewViewCell{
var imageTappedDelegate : ImageTappedDelegate!
}
class NewsFeedVideoTableViewViewCell : NewsFeedTableViewViewCell{
var videoTappedDelegate : VideoTappedDelegate!
}
要解决您的问题,请在分配委托之前强制转换为正确的类型。每当您引用单元格时,其类型为 UITableViewCell,因此您的自定义子类上的那些属性/方法不存在。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell : NewsFeedTableViewViewCell!
if let url = media.url {
if Helper.isImageType(url: url)
{
cell = tableView.dequeueReusableCell(withIdentifier: newsFeedImageTableViewViewCellId, for: indexPath) as! NewsFeedImageTableViewViewCell
(cell as ! NewsFeedImageTableViewCell).imageTappedDelegate = self
}else
{
cell = tableView.dequeueReusableCell(withIdentifier: newsFeedVideoTableViewViewCellId, for: indexPath) as! NewsFeedVideoTableViewViewCell
(cell as! NewsFeedVideoTableViewCell).videoTappedDelegate = self
}
cell.linkTappedDelegate = self
cell.backgroundColor = UIColor(rgb: 0xF2F2F2)
cell.isAccessibilityElement = true
cell.selectionStyle = .none
tableViewIndex = indexPath
if let _states = states?[indexPath.section]{
cell.state = _states[indexPath.row]
}
return cell
}
return UITableViewCell()
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句