swift 变量声明后,变量类型不会改变?

swift variable type won't change after downcast if the variable has been declared?

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

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

但在那之后,cell 无法访问 CellOne 实例持有的 nameLabel。我收到错误消息:"Value of type 'UITableViewCell' has no member nameLabel".

看来cell还没有降级到UITableViewCell的子类。

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

非常感谢您的宝贵时间。


这是我的代码:

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 
}

我发现最好让您的单元更通用,因为它们可以在多个 'section' 中工作。 IE。而不是 'CellOne' 将您的单元格创建为 'NameCell',它可以用于 table.

的所有部分

细胞应该是可重复使用的。

let nameCell = tableView.dequeueReusableCellWithIdentifier("nameCell") as! NameCell

switch indexPath.section{
case 0: 
  nameCell.nameLabel.text = "name1"
break
case 1:
  nameCell.nameLabel.text = "name2"
break
...
default:
  ...
}