ios - 如果变量已声明,则 swift 变量类型在向下转换后不会改变?

标签 ios swift uitableview variables downcast

我打算根据 UITableViewCell 所在的部分将其向下转换为不同的子类。

假设 UITableViewCell 的子类是 CellOne 并且它有一个 var nameLabel。在一种情况下,我将 dequeueReusableCellWithIdentifier(_:_:) 返回的 UITableViewCell 向下转换(as!)到 CellOne 并将其分配给 cell,在 switch block 外部声明为 var cell = UITableViewCell() 的变量。

但此后,cell 无法访问 CellOne 实例持有的 nameLabel。我收到错误消息:“‘UITableViewCell’类型的值没有成员 nameLabel”。

看来 cell 还没有被向下转型为 UITableViewCell 的子类。

有什么方法可以让cell访问nameLabel(在 block 外声明之后)?声明变量后,可以通过为其分配子类实例来将其向下转换为另一种类型吗?

非常感谢您抽出时间。


这是我的代码:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = UITableViewCell()

    switch indexPath.section {
    case 0:
        cell = tableView.dequeueReusableCellWithIdentifier("cellOne", forIndexPath: indexPath) as! CellOne
        cell.nameLabel.text = "one" // Error: Value of type 'UITableViewCell' has no member 'nameLabel'
    case 1:
        cell = tableView.dequeueReusableCellWithIdentifier("cellTwo", forIndexPath: indexPath) as! CellTwo
    ...... // Other cases
    }

    return cell
}

以及 CellOne 的代码:

class CellOne: UITableViewCell {
    @IBOutlet weak var nameLabel: UILabel!
    ......
}

最佳答案

问题在于您声明变量cell的位置,您明确表示它是一个UITableViewCell,因此您将无法将其向下转换为yourCustomCell >.

更改此:

  var cell = UITableViewCell()

Based on your comment you want to use multiple custom cells

我认为您应该在案例代码块中声明这些海关单元

 switch indexPath.section 
{
  case 0:
    let cell = tableView.dequeueReusableCellWithIdentifier("cellOne", forIndexPath: indexPath) as! CellOne
      cell.nameLabel.text = "one"
  case 1:
     let secondCell = tableView.dequeueReusableCellWithIdentifier("cellTwo", forIndexPath: indexPath) as! CellTwo
       // do whatever you want 
}

关于ios - 如果变量已声明,则 swift 变量类型在向下转换后不会改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32976539/

相关文章:

ios - 仅在指定部分启用 UITableView 编辑

ios - 在 Fabric.io 中过滤一段时间内的数据

javascript - 拍照时 React-native iOS 应用程序崩溃

swift - Swift 中的观察者模式

ios - 无法在 UITableViewCell 中呈现

ios - 如何将 segue 从 TableView 中的单元格单击推送到另一个 View Controller

ios - (iOS) 如何使用 shapeLayer 为圆角矩形制作动画?

ios - 我应该怎么办?在 SpriteKit swift 中它说 : Type 'GameScene' does not conform to protocol 'GKGameCenterControllerDelegate' ?

ios - 将扩展标记为 @objc 仅用于单元测试

iphone - 自定义表格单元格加载数据 Objective C iOS -