SoFunction
Updated on 2025-04-13

iOS development learning TableView displays a list instance

TableView Basics

This article talks about the basic use of TableView. By the way, introduce the delegation.

What TableView is used for

TableView is used to display a very long list. Unlike the RecyclerView in Android, TableView in iOS can only be a vertical list.

How to write a simplest TableView

One of the easiest TableViewController looks like this:

class ViewController: UITableViewController {
    var data: [String] = []
    override func viewDidLoad() {
        ()
        // Do any additional setup after loading the view.
        // loadData()
        print(data)
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = (withIdentifier: "MyCell", for: indexPath)
        ?.text = data[]
        return cell
    }
}

Here data is the data type you want to display, you can hardcode some data.

It's so simple because this ViewController inherits itUITableViewController, and the cell part uses storyboard.

Need to use it heredequeueReusableCellThe method is for cell reuse, because when the list content is very large, cell view can be recycled. (It's very similar to the RecyclerView in Android).

UITableViewControllerThe signature is like this:

open class UITableViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {

It did the following three things for us:

  • Set view to oneUITableView.
  • set updelegate=self.
  • set updataSource=self.

The limitation of this approach lies in the first point, its root view is a TableView. If our needs are more complicated, not just a demo, then we may need to combine Views.

Disassembled TableView

We can also inherit directlyUIViewControllerclass, and then do the above settings yourself.

Delegate & DataSource

There are two important aspects of TableView that need attention:

  • UITableViewDelegate: manages interactions with users, such as selection, swipe gestures, etc. There is no way to implement it.
  • UITableViewDataSource: Provides and manages data, including the cell or header corresponding to the data. There are two methods that must be implemented (as shown in the above code example).

Inherit UIViewController

Inherit UIViewController instead ofUITableViewControllerAfter that, you need to write a tableView yourself and add it to the view. Then implement it separatelyUITableViewDelegateandUITableViewDataSource, This is written in the extension, after splitting, set to the tableView:

 = self
 = self

The overall code after the transformation is as follows:

class ViewController: UIViewController {
    var data: [String] = ["Hello", "World"]
    private let tableView = UITableView()
    override func loadView() {
        view = UIView()
        (tableView)
         = false
        ([
            (equalTo: ),
            (equalTo: ),
            (equalTo: ),
            (equalTo: ),
        ])
    }
    override func viewDidLoad() {
        ()
        (, forCellReuseIdentifier: "MyCell")
         = self
         = self
    }
}
extension ViewController: UITableViewDelegate {}
extension ViewController: UITableViewDataSource {
    func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
        
    }
    func tableView(_: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = (withIdentifier: "MyCell", for: indexPath) as? MyCell {
            (with: data[])
            return cell
        }
        return UITableViewCell()
    }
}

Your own Cell class

Here, Cell also uses code classes instead, and writes a class like this:

class MyCell: UITableViewCell {
    private let label = UILabel()
    override init(style: , reuseIdentifier: String?) {
        (style: style, reuseIdentifier: reuseIdentifier)
        (label)
         = false
        ([
            (equalTo: ),
            (equalTo: ),
            (equalTo: ),
            (equalTo: ),
        ])
    }
    @available(*, unavailable)
    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func configure(with data: String) {
         = data
    }
}

Note that tableView registers this Cell type:

override func viewDidLoad() {
        ()
        (, forCellReuseIdentifier: "MyCell")
}

Supplementary knowledge: Delegation

The above method may be very strange at first glance. Here we also involve a knowledge point, delegate in iOS. Its existence is to expand the functions of its own class.

Many of Apple's own APIs use delegate protocol, for exampleUIApplicationDelegate, UITableViewDelegate. If we want to define one ourselves:

protocol MyTypeDelegate: AnyObject {
    func myType(_ myType: MyType,
                      shouldDoSomething argumentString: String) -> Bool
    func myType(_ myType: MyType,
                      didAbortWithError error: Error)
    func myTypeDidFinish(_ myType: MyType)
}
class MyType {
    weak var delegate: MyTypeDelegate?
}

Several principles for defining delegation:

  • The method name begins with the type that is proxyed.
  • The first parameter of the method is the proxy object.

References

Filling a table with data

Table View Guide

The above is the detailed content of the iOS series learning TableView to display a list example. For more information about iOS TableView to display list, please follow my other related articles!