我打算根据 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/