ios tableview example for displaying list of items
Contact.swift, this will be the data to be displayed in each row in the table view.
import Foundation
struct Contact {
var name: String
var title: String
}
DataFactory.swift, this is a factory class to create a list of data items for displaying in the tableview.
import Foundation
class DataFactory {
static func generatContacts() -> [Contact] {
var contacts: [Contact] = []
for index in 0...30 {
contacts.append(Contact(name: "name\(index)", title: "title \(index)"))
}
return contacts
}
}
ContactTableViewCell.swift, this is the view class which models the views in the table cell. We are going to display an UIImageView, and two UILabels in each table cell. Hence, we have defined an UIImageView and two UILabels in this view class.
import UIKit
class ContactTableViewCell: UITableViewCell {
@IBOutlet weak var portraitImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
ContactTableViewController.swift, the tableview controller implementation for displaying a simple list of contacts. let cellIdentifier = "tableCell" this tableCell is defined in the storyboard, and it is used to find each table cell and renders the data in it.
import UIKit
class ContactTableViewController: UITableViewController {
var contacts: [Contact] = []
override func viewDidLoad() {
super.viewDidLoad()
contacts = DataFactory.generatContacts()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #return the number of rows
return contacts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "tableCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? ContactTableViewCell
else {
fatalError("The dequeued cell is not an instance of ContactTableViewCell.")
}
// Configure the cell
let contact = contacts[indexPath.row]
cell.portraitImageView.image = UIImage(named: "portrait_placeholder")
cell.nameLabel.text = contact.name
cell.titleLabel.text = contact.title
return cell
}
}
Make sure to do the following:
Defining the tableCell identifier in the storyboard.
Connecting the table cell with the custom made view ContactTableViewCell
Connecting the view controller from storyboard to it’s view controller class.
Search within Codexpedia
Search the entire web