Swift 自定义单元格创建您自己的带有标签的单元格

Swift Custom Cell creating your own Cell with labels

我刚开始使用 Swift 作为编程语言,我 运行 遇到了自定义单元格的问题。

当我尝试创建自定义单元格,然后继续尝试按照我需要的方式设计它们(样式设置为自定义)时,一切看起来都不错。现在我不知道如何将特定数据放入其中,因为我找到的所有教程都使用样式选项 "basic",其中它们只有一个文本标签,他们将数据分配给它们。

现在对我来说,当我 "control drag" 我的标签到我的代码中时,我给它们指定特定的名称,例如 "dateLabel" 或 "sourceLabel" 以便正确插入数据。

现在我不确定,也找不到任何有效的答案,关于如何调用我的定制标签以便我可以将我的数据分配给它们...

也许你们中有人可以帮我解决这个问题,因为我很确定这是一个简单的问题,但我找不到任何相关资源 ^^

希望字体不要太小,我只是想让你们看看我得到的错误。

我使用以下教程作为指导,因为这是唯一一个按照这个人的方式工作的教程:https://www.youtube.com/watch?v=0qE8olxB3Kk

我检查了标识符,他设置正确,但我在网上找不到任何关于如何正确引用我自己的标签及其正确名称的信息。

任何帮助将不胜感激:)

请尝试以下步骤:

  1. 创建扩展 UITableViewCell 的自定义 table 视图单元格 class。在我的示例中,自定义 table 视图单元格 class 称为 MyCustomTableViewCell.

  2. 更新故事板的单元格,使其使用自定义 table 视图单元格 class。转到 Identity Inspector 并将 Class 值设置为自定义 table 视图单元格 class 的名称。

  3. 更新故事板的单元格并赋予它 重用身份 值。转到 Attributes Inspector 并设置 Identifier 值。例如,我为我的单元格指定了一个标识符值 MyCustomCell

  4. 控制将单元格的标签拖动到新的自定义 table 视图单元格 class(即 MyCustomTableViewCell class)。


完成上述步骤后,当您在 tableView:cellForRowAtIndexPath: 方法中 dequeue 您的单元格时,您将能够访问标签。正如下面的代码片段所示,您将需要:1) 使用您在上述步骤中建立的 重用标识符 获取单元格,以及 2) 转换为您的自定义 table 视图单元格 class.

例如,如果您将自定义 table 视图单元命名为 MyCustomTableViewCell,这就是它的样子。这是在您创建 class 并控制将您的标签拖到此 class 之后。

class MyCustomTableViewCell: UITableViewCell {    
    @IBOutlet weak var categoryLabel: UILabel!
    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var sourceLabel: UILabel!
    @IBOutlet weak var titleLabel: UILabel!
} 

您的 ViewController 可能如下所示:

// NOTE: I subclassed UITableViewController since it provides the
// delegate and data source protocols. Consider doing this.
class ViewController: UITableViewController {

    // You do NOT need your UILabels since they moved to your
    // custom cell class.

    // ...
    // Omitting your other methods in this code snippet for brevity.
    // ... 

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

        // Use your cell's reuse identifier and cast the result
        // to your custom table cell class. 
        let article = tableView.dequeueReusableCellWithIdentifier("MyCustomCell", forIndexPath: indexPath) as! MyCustomTableViewCell

        // You should have access to your labels; assign the values.
        article.categoryLabel?.text = "something"            
        article.dateLabel?.text = "something"            
        article.sourceLabel?.text = "something"            
        article.titleLabel?.text = "something"            

        return article
    }
}