UITableView example for Swift

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

I've been working with Swift and iOS for a number of months now. I am familiar with many of the ways things are done but I'm not good enough that I can just write things up without looking. I've appreciated Stack Overflow in the past for providing quick answers to get me back on track with topics I've gotten rusty on (for example, AsyncTask Android example).

iOS's UITableView is in this category for me. I've done them a few times, but I forget what the details are. I couldn't find another question on StackOverflow that just asks for a basic example and I'm looking for something shorter than many of the tutorials that are online (although this one is very good).

I am providing an answer below for my future reference and yours.

回答1:

The example below is an adaptation and simplification of a longer post

Create a New Project

It can be just the usual Single View Application.

Add the Code

Replace the ViewController.swift code with the following:

import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {      // Data model: These strings will be the data for the table view cells     let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]      // cell reuse id (cells that scroll out of view can be reused)     let cellReuseIdentifier = "cell"      // don't forget to hook this up from the storyboard     @IBOutlet var tableView: UITableView!      override func viewDidLoad() {         super.viewDidLoad()          // Register the table view cell class and its reuse id         self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)          // (optional) include this line if you want to remove the extra empty cell divider lines         // self.tableView.tableFooterView = UIView()          // This view controller itself will provide the delegate methods and row data for the table view.         tableView.delegate = self         tableView.dataSource = self     }      // number of rows in table view     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {         return self.animals.count     }      // create a cell for each table view row     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {          // create a new cell if needed or reuse an old one         let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!          // set the text from the data model         cell.textLabel?.text = self.animals[indexPath.row]          return cell     }      // method to run when table view cell is tapped     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {         print("You tapped cell number \(indexPath.row).")     } } 

Read the in-code comments to see what is happening. The highlights are

  • The view controller adopts the UITableViewDelegate and UITableViewDataSource protocols.
  • The numberOfRowsInSection method determines how many rows there will be in the table view.
  • The cellForRowAtIndexPath method sets up each row.
  • The didSelectRowAtIndexPath method is called every time a row is tapped.

Add a Table View to the Storyboard

Drag a UITableView onto your View Controller. Use auto layout to pin the four sides.

Hook up the Outlets

Control drag from the Table View in IB to the tableView outlet in the code.

Finished

That's all. You should be able run your app now.

This answer was tested with Xcode 9 and Swift 4


Variations

Row Deletion

You only have to add a single method to the basic project above if you want to enable users to delete rows. See this basic example to learn how.

Row Spacing

If you would like to have spacing between your rows, see this supplemental example.

Custom cells

The default layout for the table view cells may not be what you need. Check out this example to help get you started making your own custom cells.

Dynamic Cell Height

Sometimes you don't want every cell to be the same height. Starting with iOS 8 it is easy to automatically set the height depending on the cell content. See this example for everything you need to get you started.

Further Reading



回答2:

For completeness sake, and for those that do not wish to use the Interface Builder, here's a way of creating the same table as in Suragch's answer entirely programatically - albeit with a different size and position.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {      var tableView: UITableView = UITableView()     let animals = ["Horse", "Cow", "Camel", "Sheep", "Goat"]     let cellReuseIdentifier = "cell"      override func viewDidLoad() {         super.viewDidLoad()          tableView.frame = CGRectMake(0, 50, 320, 200)         tableView.delegate = self         tableView.dataSource = self         tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)          self.view.addSubview(tableView)     }      func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {         return animals.count     }      func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {         let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell!          cell.textLabel?.text = animals[indexPath.row]          return cell     }      func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {         print("You tapped cell number \(indexPath.row).")     }  } 

Make sure you have remembered to import UIKit.



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