brief introduction
Table view is a view that displays the contents row by row. Each row is called a Cell. iOS has only one Cell per row by default. Cells support customization.
Cells are divided into dynamic and static. Dynamic refers to the automatic generation of cells during program operation. It is generally used when the specific number of cells is not known in advance. If it is a static Cell, you can directly drag and drop the required quantity to the TableView in the StoryBoard. The preset Cell can put a picture, a paragraph of text and an indicator (located on the far right of the Cell).
UICollectionView is very similar to TableView. The difference is that CollectionView supports putting multiple cells in each line. Cells beyond the right boundary of the screen will be automatically arranged to the next line, and will be automatically rearranged when the iPad device rotates. In addition, it supports custom Cell layout methods (such as waterfall flow layout commonly used in e-commerce projects).
Three conversations in the table
If you want to use the TableView view, you need to hand it over to a ViewController to manage it. This ViewController needs to follow the UITableViewDataSource and UITableViewDelegate protocols. The former is used to set the TableView data source, and the latter is used to set the TableView structure and control TableView related events.
func viewDidLoad() { tableView.datasource = self tableView.delegater = self }
- In the first stage of dialogue, how many sections are there in the table (the Cell and layout of different sections can be different)
func numberOfSection(in tableView: UITableView) -> Int { return 1 }
- In the second stage of dialogue, how many cells are there in each section
func tableView(_ tableView: UITableView, numberOfRowsInSection section: nil) { return 3 }
- In the third stage, what is the content of each Cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) //If it is a custom Cell, you need to register it in ViewController first, and then resolve it in this way. The parameter after withIdentifier is the identification name of the Cell. return cell }
Which Cell is selected
There are two ways to know which Cell has been selected:
- Implement the tableview (: didselectedrowat:) function, which can be determined by parameters.
func tableView(_ tableView: UITableView, didSelectedRowAt indexPath: IndexPath) { print(indexPath.row) }
- Through the indexPathForSelectedRow property of TableView.
let indexPath = tableView.indexPathForSelectedRow
Change the order of cells
When the table enters the editing state, the user can change the position of the Cell by dragging and dropping with his finger. However, it should be noted that if the data source does not change, the order will be restored after the table is rearranged.
- First, set the table to edit mode (e.g. when clicking a button)
tableView.isEditing = true
- Implement tableView(:canMoveRowAt:) and tableView(:moveRowAt:) functions. Note that the order of data sources should also change (take list array as an example)
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return true }
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { list.insert( list.remove(at: sourceIndexPath.row), at: destinationIndexPath.row ) }
- If you do not want the user to delete the Cell after entering the edit mode, you need to implement tableview (: editingstyleforrowat:) and return it none
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { return .none }
Delete Cell
When the user slides the Cell to the left, "Delete" or "Delete" will appear on the right of the Cell. Click to Delete the Cell.
- Implement the tableview (: commit: forrawat:) function to delete the data in Cell and Cell (also take the list array as an example)
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRawAt indexPath: IndexPath) { list.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .automatic) }
- The default red "Delete" or "Delete" can be changed
func tableView(_ tableView: UITableView, titileForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? { return "Delete this Cell" }
Refresh table data
When the table data source changes, directly call tableview Reloaddata() function.
Pull down refresh
Compared with clicking the refresh button to refresh the table, the pull-down gesture is more comfortable to edit. TableView has built-in pull-down refresh function.
- First, implement the handleRefresh() function to handle the refresh logic
@objc func handleRefresh() { let formatter = DateFormatter() fomatter.dateFormat = "hh:mm:ss" let time = formatter.string(from: Date()) list.append(time) tableView.refreshControl?.endRefreshing()//Stop the drop-down animation and restore the table to its original position tableView.reloadData() }
- Bind events in the viewDidLoad() function
override func viewDidLoad() { super.vieDidLoad() tableView.refreshControl = UIRefreshControl() tableview.refreshControl?.addTarget(self, action: #selector(handleRefresh), for: .valueChanged) }
- You can set the prompt text in viewDidAppear(:)
override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) tableView.refreshControl?.attributeTitle = NSAttributeString(string: "Updating...") }
Slide left or right button of Cell
When you slide the Cell on the left, a delete button will appear on the right. In addition to the delete button, you can also set other buttons. You can also set the button that appears on the right slide.
For left sliding, the tableview (: trailingswipeactionsconfigurationforrowat:) function needs to be implemented; The right slide needs to implement the tableview (: leadingswapeactionsconfigurationforrowat:) function. (take left sliding as an example)
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let go = UIContextAction(style: .normal, title: "more") { (action, view, completionHandler) in //Press the button to do completionHandler(true) } go.backgroundColor = .blue let del = UIContextAction(style: .destructive, title: "delete") { (action, view, completionHandler) in //Press the button to do completionHandler(true) } let config = UISwipeActionsConfiguration(actions: [go, del]) config.performsfirstActionWithFullSwipe = false return config }
Cell height
The height of the Cell is consistent with the content in the Cell by default
Header and Footer
You can set the Header and Footer styles of each Section, which are not displayed by default.
Take Header as an example:
- Set title text only
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "title" }
- Set custom View
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> UIView? { return yourView }
- Change the default height of Header
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 20 }