[Swift] Template (like) when creating Table View

What is this

The code I write almost every time I create a Table View is summarized like a template.

Object placement

  1. Place Table View on the storyboard
  2. Place Table View Cell on top of the placed Table View

Edit ViewController

  1. Control-drag and drop Table View onto the view controller
  2. Add protocols (DataSource and Delegate) so that they can be used

ViewController.swift


class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

  //The part where you dragged and dropped the Table View
  @IBOutlet weak var tableView: UITableView!
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    tableView.delegate = self
    tableView.dataSource = self
  }

I just added a protocol

Type 'ViewController' does not conform to protocol 'UITableViewDataSource'

I get the error. If you press fix in a place where" there is no required method ", methods related to" number of cells "and" building cells "will be created automatically.

Number and construction of cells

--Number of cells. Return as a number --Select Table View Cell on the storyboard and write any name in Identifier. I wrote "Cell" here --Added method dequeueReusableCell for cell reuse

ViewController.swift


  //Number of cells
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
  }
  
  //Building a cell
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    
    //Other things I want to do

    return cell
  }

Cell height

Use a delegate method called heightForRowAt. This is not added automatically even if you press fix as described above, so write it yourself.

ViewController.swift


  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 200
  }

Please let me know if there is something missing yet.

Recommended Posts

[Swift] Template (like) when creating Table View
View photos like Pinterest
[Swift] Table View Cell, how to jump to an external URL