I have a table view with many table view cells. When the user clicks on a cell, I want to update the cell's label text.
Here is my table view controller class:
class MyTableViewController: UITableViewController {
var data = [Data]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
// Here I fetch and populate the data list
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "MyTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? MyTableViewCell else {
fatalError("The dequeued cell is not an instance of MyTableViewCell.")
}
let cellData = data[indexPath.row]
cell.initialize(data: cellData)
return cell
}
}
And here is my table view cell class:
class MyTableViewCell: UITableViewCell {
var data: Data?
#IBOutlet weak var nameLabel: UILabel!
func initialize(data: Data) {
self.data = data
if let cellName = data.name {
nameLabel.text = cellName
}
}
}
How can I change the text of the nameLabel above (to "Clicked") when the user clicks on the table view cell?
There're no doubt different ways you could handle this, but here is what I would suggest:
Implement the UITableViewDelegate methods tableView(_:didSelectRowAt:) and tableView(_:didDeselectRowAt:). Add a selected bool to the data model for the cells in your table view, and update the state of that bool as the cells are selected/deselected.
Then modify your cellForRow(at:) method so it uses the selected flag to decide what to show in your label.
Finally, have your tableView(_:didSelectRowAt:) and tableView(_:didDeselectRowAt:) methods tell the table view to reload the newly selected/deselected cell.
class TableController: UIViewController {
#IBOutlet var ListTable: UITableView!
var list: [Dictionary<String, String>] = []
override func viewDidLoad() {
super.viewDidLoad()
let ListTable = UITableView(frame: view.bounds)
self.ListTable = ListTable
ListTable.dataSource = self
ListTable.delegate = self
initList()
}
func initList() {
// get list from firebase
self.ListTable.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return list.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = self.list[indexPath.row]
let cellIdentifier = "ListCell"
let cell = CustomCell(style: .default, reuseIdentifier: cellIdentifier)
cell.foodLabel?.text = item["Banana"]
return cell
}
}
extension QueueController: UITableViewDataSource, UITableViewDelegate {
}
CustomCell class:
import UIKit
class CustomCell: UITableViewCell
{
#IBOutlet weak var foodLabel: UILabel!
override func awakeFromNib()
{
super.awakeFromNib()
}
}
My data from firebase loads properly. On storyboard I have a normal view controller with a UITableView embedded inside of it. That table view is liked to my IBOutlet for my ListTable. In the table there is a cell with 3 labels. That cell has the identifier ListCell and it's class is CustomCell.
Edit: There is no error but my data isn't showing up.
This is because your Custom Cell does not dequeue properly. Try this one
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "ListCell"
var cell : ListCell? = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! ListCell?
if (cell == nil) {
cell = Bundle.main.loadNibNamed("ListCell", owner: nil, options: nil)?[0] as? ListCell
}
cell?.backgroundColor = UIColor.clear
cell?.contentView.backgroundColor = UIColor.clear
return cell!
}
Perhaps try registering your cell in viewDidLoad
ListTable.register(UINib(nibName: "CustomCell", bundle: Bundle.main), forCellReuseIdentifier: "ListCell") //this is assuming that your nib is named "CustomCell"
Also, for the record, you should follow camel-case conventions and name your UITableView listTable
You did never add the TableView to your view... (or part go the code is missing )
I am new to iOS dev and basically I'm trying to populate a TableView with String values from an array.
However when I run the app, blank rows show up and no text values are shown. Have I coded this correctly?
import UIKit
class SelectIssueController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var issuesTableView: UITableView!
var issues = [Issue]()
override func viewDidLoad() {
super.viewDidLoad()
self.issues = ["Test1", "Test2", "Test3"]
self.issuesTableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
override var preferredStatusBarStyle: UIStatusBarStyle{
return UIStatusBarStyle.lightContent
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.issues.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.issuesTableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell
cell.textLabel?.text = issues[indexPath.row]
//Even if I manually set a value, the rows are still blank
//cell.textLabel?.text = "Hello World"
return cell
}
}
You can set Table view data source and delegate in two ways.
1. Click Cntrl+drag from tableView to view controller. See below figure
Create the outlet of your tableView and assign its datasource and delegate in ViewDidLoad.
In your example you already have an outlet to issuesTableView, so you would write:
issuesTableView.dataSource = self
issuesTableView.delegate = self
Thanks:)
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.
The example below is an adaptation and simplification of a longer post from We ❤ Swift. This is what it will look like:
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
iOS & Swift Tutorial: UITableViewController
iOS Table View Tutorial Using Swift
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.
In Swift 4.1 and Xcode 9.4.1
Add UITableViewDataSource, UITableViewDelegate delegated to your class.
Create table view variable and array.
In viewDidLoad create table view.
Call table view delegates
Call table view delegate functions based on your requirement.
import UIKit
// 1
class yourViewController: UIViewController , UITableViewDataSource, UITableViewDelegate {
// 2
var yourTableView:UITableView = UITableView()
let myArray = ["row 1", "row 2", "row 3", "row 4"]
override func viewDidLoad() {
super.viewDidLoad()
// 3
yourTableView.frame = CGRect(x: 10, y: 10, width: view.frame.width-20, height: view.frame.height-200)
self.view.addSubview(yourTableView)
// 4
yourTableView.dataSource = self
yourTableView.delegate = self
}
// 5
// MARK - UITableView Delegates
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell : UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cell")
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
}
if self. myArray.count > 0 {
cell?.textLabel!.text = self. myArray[indexPath.row]
}
cell?.textLabel?.numberOfLines = 0
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50.0
}
If you are using storyboard, no need for Step 3.
But you need to create IBOutlet for your table view before Step 4.
SWIFT 5
If you only want a tableView on your screen then you can implement UITableViewController to your ViewController and do like this to show a simple tableViewController with a label in it.
Swift file
class ToDoListViewController: UITableViewController {
let array = ["GAFDGSG","VSBFFSB","BFBFB"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
array.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoItemCell", for: indexPath)
cell.textLabel?.text = array[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(indexPath)
}
}
And in storyboard create a UITableViewController with mentioning the identifier like this
MainStoryboard
Result
Here is the Swift 4 version.
import Foundation
import UIKit
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 = CGRect(x: 0, y: 50, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
self.view.addSubview(tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return animals.count
}
internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
cell.textLabel?.text = animals[indexPath.row]
return cell
}
private func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath)
{
print("You tapped cell number \(indexPath.row).")
}
}
// UITableViewCell set Identify "Cell"
// UITableView Name is tableReport
UIViewController,UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate {
#IBOutlet weak var tableReport: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableReport.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "Report Name"
return cell;
}
}
I have a custom class that extends UIViewController and contains a table view, with an array that stores data that populates the table view. For my custom cells, I have a button that when pressed, should remove that cell from the table view. However, I haven't been able to find a way to remove the data from the array in the table view controller and reload the data from the cell's class. Some of the answers I've seen on similar posts suggest notifications or delegation, but due to the structure of my app (tab controller) and that I already use notifications for another feature, the former is inefficient, and I don't know how to use the latter in this situation.
This is the code for the custom cell class:
class CustomCell: UITableViewCell {
#IBOutlet var label: UILabel!
#IBOutlet var removeButton: UIButton!
#IBAction func remove(sender: AnyObject) {
// don't know what to put here
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
And here is the table view controller class:
class CustomController: UIViewController, UITableViewDataSource {
#IBOutlet var table: UITableView!
var data: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
table.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: CustomCell = table.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as! CustomCell
// put content in
return cell
}
}
The array data is what I want to access from remove in CustomCell. The closest I've gotten is using self.superview.superview.superview in CustomCell, which returns the view that CustomController controls. However, I have no way to get an instance of CustomController without instantiating a new one. How do I modify a variable in CustomController from the CustomCell class?
In your Custom Cell add this
class CustomCell: UITableViewCell {
var customControllerReference: CustomController?
}
And in your Custom Controller in cellForRowAtIndexPath add this
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: CustomCell = table.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as! CustomCell
cell.customControllerReference = self
return cell
}