Implementation of the List of iOS apps developed by Swift (1)
Software and hardware environment
- OS X EI Capitan
- Xcode 7.0.1
Introduction
List is one of the most important controls. In iOS, It is UITableView. This section describes how to implement a list, as shown below:
Implementation steps UI
Create a project named UITableViewDemo. select Single View as the template.
Select Table View in the control library in the lower-right corner of Xcode, hold down and drag it to the storyboard, and drag it to full screen
Set Prototype Cells of Table View to 1, then select Prototype Cells, select Basic in the Stype attempt in the attribute in the upper right corner, and set Identifier to Cell (which can be arbitrary, will be used in subsequent code files ),
Bind data to the list
After the above operation, we can see the list, but every cell is empty and there is no data
A color array is provided, and each element of the array is displayed in the corresponding cell.
var colors = ["Red","Yellow","Green","Gray","Orange","Black","White"]
In the ViewController class, you must implement the UITableViewDataSource and UITableViewDelegate protocols, and then implement two methods.
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return colors.count }
Returns the size of the given array, which is the number of rows in the list.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) cell.textLabel?.text = colors[indexPath.row] return cell }
The above "Cell" is the Identifier in the storyboard. This function returns a cell with a string of characters displayed on the cell. The dequeueReusableCellWithIdentifier method reuse cells to improve efficiency and save resources. A common message list is like a message list in Weibo. Each screen of a device displays only a few messages, and the drop-down refresh is performed once. The cells are still the messages, but the content is refilled.
In the last step, switch to the storyboard, Open View Controller Scene, bind the Table View and View Controller, hold down the control key, and drag Table View to View Controller, repeat once and select delegate
So far, the data in the list is correctly displayed. You can view it on the simulator.
Source code download
Https://github.com/djstava/SwiftForiOS/tree/master/TableViewDemo