create a tableview with 10 items in swift

To create a tableview with 10 items in Swift, follow these steps:

  1. Open Xcode and create a new project.
  2. Select "Single View App" as the project template.
  3. Enter a product name and organization identifier for your app.
  4. Under "User Interface," select "Storyboard" and click "Create."
  5. Drag a tableview from the object library onto your storyboard.
  6. Select the tableview and drag a "Table View Cell" onto the tableview.
  7. Click on the cell in the storyboard and give it a reuse identifier ("cellIdentifier" for example).
  8. Create a new Swift file for your view controller (File > New > File > Swift File).
  9. In the view controller file, import UIKit and conform to the UITableViewDelegate and UITableViewDataSource protocols.
  10. Implement the required UITableViewDelegate and UITableViewDataSource methods in the view controller.

Here is some sample code to create a UITableView with 10 items:

main.swift
import UIKit

class MyTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet weak var tableView: UITableView!
    
    let items = ["Apple", "Banana", "Cherry", "Durian", "Elderberry", "Fig", "Grapes", "Honeydew", "Iced melon", "Jackfruit"]
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath)
        cell.textLabel?.text = items[indexPath.row]
        return cell
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.delegate = self
        tableView.dataSource = self
    }
}
854 chars
26 lines

This code creates a UITableViewController with a list of 10 items (in the "items" array) and displays them in a tableview. The "numberOfRowsInSection" method returns the number of items (in this case, 10), and the "cellForRowAt" method configures each cell in the tableview with the corresponding text label. The reuse identifier for the cell is set to "cellIdentifier," which is used to dequeue and reuse cells in the tableview. The view controller is set as the delegate and data source for the tableview in the viewDidLoad() method.

gistlibby LogSnag