Swift Custom Cell creating your own Cell with labels

筅森魡賤 提交于 2019-12-04 05:42:49

Try the following steps:

  1. Create a custom table view cell class that extends UITableViewCell. In my example, the custom table view cell class is called MyCustomTableViewCell.

  2. Update your storyboard's cell so that it uses your custom table view cell class. Go to the Identity Inspector and set the Class value to the name of your custom table view cell class.

  3. Update your storyboard's cell and give it a reuse identity value. Go to the Attributes Inspector and set the Identifier value. For example, I gave my cell an Identifier value of MyCustomCell.

  4. Control drag the cell's labels into your new custom table view cell class (i.e., the MyCustomTableViewCell class).


Once you have done the above steps, you will be able to access the labels when you dequeue your cell in the tableView:cellForRowAtIndexPath: method. As the code snippet below shows, you will need to: 1) get the cell using the reuse identifier you established in the steps above and 2) cast to your custom table view cell class.

For example, here's what your custom table view cell would look like if you named it MyCustomTableViewCell. This is after you created the class and control dragged your labels into this class.

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

Your ViewController could look like this:

// 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
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!