我意欲基于它是英寸如果声明了变量,swift变量类型在downcast后不会改变?
假设的UITableViewCell的子类是CellOne
,它有一个其var nameLabel
部向下转换到一个UITableViewCell到不同的子类。在一种情况下,我倒下(如!)由dequeueReusableCellWithIdentifier(_:_:)
返回到CellOne
的UITableViewCell,并将其分配给cell
,在变换块外部声明为var cell = UITableViewCell()
的变量。
但是之后,cell
无法访问nameLabel
即CellOne
实例。我收到错误消息:“类型'UITableViewCell'的值没有成员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'声明为'CellOne',因为它可能会根据它所在的部分被降频到UITableViewCell的其他子类(如CellTwo,CellThree ...)。所以我无法将其声明为'CellOne ”。我会编辑这个问题,使其更清晰。 – ninikikki
所以如果你正在使用其他自定义单元格,你应该只在同一个代码块中声明 – Lamar
我不想重复“return cell”多次。但我想我没有其他选择=)非常感谢! – ninikikki