【问题标题】:How to get UITableViewCell object from indexPath in Swift?如何从 Swift 中的 indexPath 获取 UITableViewCell 对象?
【发布时间】:2014-09-25 12:19:01
【问题描述】:

我正在尝试使用 Swift 以编程方式获取 UITableViewCell 对象,因此我编写了以下代码:

let cell:UITableViewCell = (UITableViewCell) UITableView.cellForRowAtIndexPath(indexPath.row)

但编译错误为:

无法将类型“(UITableViewCell).Type”的值转换为指定类型“UITableViewCell”
一行中的连续语句必须用';'分隔
实例成员 'cellForRowAtIndexPath' 不能用于类型 'UITableView';你的意思是使用这种类型的值吗?

【问题讨论】:

    标签: ios uitableview swift


    【解决方案1】:

    cellForRowAtIndexPath 不是类方法。请改用实例方法。

    let cell = tableView.cellForRowAtIndexPath(indexPath)
    

    斯威夫特 3:

    let cell = tableView.cellForRow(at: indexPath)
    

    【讨论】:

    • cellForRowAtIndexPath 确实将索引路径作为参数。
    • 我在上面的代码中无法访问。我在这里使用自定义单元格。
    • 知道了。实际上 heightForRowAtIndexPath 在 cellForRowAtIndexPath 之前被调用,这就是我遇到问题的原因。
    • @iThink,那你做了什么?我有同样的问题,我必须得到一个单元格标签的大小
    • 计算大小而不调用cellForRowAtIndexPath
    【解决方案2】:

    您可以将其用于 Swift 4

    let indexPath = IndexPath(row: 0, section: 0)
    let cell = tableView.cellForRow(at: indexPath)
    

    【讨论】:

      【解决方案3】:

      首先获取你想去的行号,然后调用下面的代码。

      let indexPath = IndexPath(row: rowNumber, section: 0)
      let tableViewCell = YourTableView.cellForRow(at: indexPath)
      

      【讨论】:

      • 请不要只发布代码作为答案,而是说明您的代码的作用以及它如何解决问题的问题。带有解释的答案通常质量更高,更有可能吸引投票。
      【解决方案4】:

      Swift 5 简易解决方案

      //MARK:- Collection View
      let cell = yourcollectionview.cellForItem(at: indexPath) as! YourCollectionViewCell
      

      表格视图

      let cell = tableView.cellForRow(at: indexPath) as! YourTableViewCell
      

      用法

      let tempImage = cell.yourImageView.image!
      

      【讨论】:

        猜你喜欢
        • 2014-11-10
        • 2013-03-20
        • 2014-07-27
        • 1970-01-01
        • 2011-01-23
        • 1970-01-01
        • 1970-01-01
        • 2013-04-20
        • 1970-01-01
        相关资源
        最近更新 更多