【问题标题】:Can we downcast to UItableview to UItableviewcell?我们可以将 UItableview 转换为 UItableviewcell 吗?
【发布时间】:2018-12-23 06:24:17
【问题描述】:

我们可以将UITableview 转换为UITableviewCell 吗?

据我所知,我很困惑,向下转换是超类和子类之间的过程,但在下面的编码中

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell=tableView.dequeueReusableCell(withIdentifier: "Categorycell")as? CategoryCell{
        let category=DataService.instance.getCategories()[indexPath.row]
        cell.updateViews(categories: category)
        return cell

    }else{
        return CategoryCell()
     }
   }

UITableview 已向下转换为 UItableviewCell 但我跳过那些类型定义两者都不相关(通过层次结构)

 class CategoryCell: UITableViewCell {

    @IBOutlet weak var categoryImage:UIImageView!
     @IBOutlet weak var categoryTitle:UILabel!

    func updateViews(categories:Category) {
        categoryImage.image=UIImage(named: categories.imageName)
        categoryTitle.text=categories.title
    }

 }

【问题讨论】:

  • "Can we downcast to UItableview to UItableviewcell?",不。你想达到什么目的?
  • 既然你没有在你的代码示例中贬低他们,你说我看不到这个问题的重点。

标签: swift


【解决方案1】:

在您的代码中,您不会从 UITableView 向下转换为 UITableViewCell。在函数cellForRowAt 中,您只是将可重复使用的单元格出列,而这些单元格是您向下转换为自定义表格视图单元格的单元格,即CategoryCell

【讨论】:

    【解决方案2】:

    回答您的问题“我们可以将 UItableview 转换为 UItableviewcell 吗?”没有。在dequeueReusableCell(withIdentifier:) 中,您实际上将UITableViewCell 转换为CategoryCell,因为所有表格单元格的父类都是UITableViewCellUITableView 上的函数dequeueReusableCell(withIdentifier:) 总是返回UITableViewCell 类型的对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2019-01-03
      • 2011-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多