2016-10-28 26 views
-2

这是我收到的错误。我确信这是一个简单的解决方法,但我遇到了一些麻烦。我更新了这个线程来添加代码。“无法将'UITableViewCell'类型的值转换为'UILabel'”

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    // #warning Incomplete implementation, return the number of rows 
    return 5 
} 


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCell(withIdentifier: "CheckListItem", for: indexPath) 

    let label = cell.viewWithTag(1000) as! UILabel 

    switch indexPath.row { 
    case 0: 
     label.text = "Walk the dog" 
    case 1: 
     label.text = "Brush my teeth" 
    case 2: 
     label.text = "Learn iOS development" 
    case 3: 
     label.text = "Soccer practice" 
    case 4: 
     label.text = "Eat ice cream" 
    default: 
     label.text = "Nothing" 
    } 
    return cell 
} 

Screenshot

+2

您是否在标签或单元格上设置了标签?另外,你真的不应该使用标签。子类化您的单元格,并在单元格子类的标签和属性之间设置一个出口。 –

+1

请不要将代码作为图片发布。请将相关代码作为文本复制并粘贴到您的问题中。它使得阅读起来更容易,并且在回答时更容易参考。 – rmaddy

+0

谢谢。我必须在标签上设置标签,而不是单元格。 –

回答

0

这是viewWithTag(_:)的功能是什么:

返回与 特定的标签,或无视图的最近后代(包括自身),如果没有子视图有标签。

所以你回来的是对象本身以及其最近的后代。它看起来像你只是想设置单元格中的文本,所以你可以做什么只是改变你的代码如下:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCell(withIdentifier: "CheckListItem", for: indexPath) 

    switch indexPath.row { 
    case 0: 
     cell.textLabel.text = "Walk the dog" 
    case 1: 
     cell.textLabel.text = "Brush my teeth" 
    case 2: 
     cell.textLabel.text = "Learn iOS development" 
    case 3: 
     cell.textLabel.text = "Soccer practice" 
    case 4: 
     cell.textLabel.text = "Eat ice cream" 
    default: 
     cell.textLabel.text = "Nothing" 
    } 
    return cell 
} 
0

我工作过的iOS学徒系列和刚刚遇到了同样的问题,你做到了。

我想你可能想检查一下标签的位置:1000到Main.storyboard - 如果你因为这个原因失败了,你可能已经把标签附加到了UITableViewCell而不是标签(在内容视图下键入UILabel)。

相关问题