i want to make table in swift

To create a table in Swift, you need to use a UITableView. Here is an example of how to create a basic table view:

  1. First, create a new project in Xcode and select "Single View App" template.

  2. Add a UITableViewController to your storyboard.

  3. In the UITableViewController class file, you'll need to define the data source for your table view. This is usually done by implementing the UITableViewDataSource protocol in your view controller.

main.swift
class ViewController: UITableViewController, UITableViewDataSource {
    
    let data = ["Item 1", "Item 2", "Item 3"]
    
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }
    
    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = data[indexPath.row]
        return cell
    }

}
861 chars
29 lines
  1. In the above code, we define an array of data to display in our table view. We also implement the required UITableViewDataSource methods which tell our table view how many rows and sections to display, as well as what data to display in each cell.

  2. Finally, we need to register a cell class for our table view. In this example, we're just using a standard UITableViewCell, but you can create your own custom cell classes if you need to display more complex data.

That's it! You now have a basic table view that displays some data. Of course, you can customize the display of your table view further by changing its appearance, adding header and footer views, and implementing UITableViewDelegate methods to handle user interactions with your table view.

gistlibby LogSnag