Why cellForRowAtIndex doesn't run at all? - ios

I've added TableView to my controller and created custom UITableViewCell. Later, I've tried to run this code:
func tableView(educationTableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> educationCell {
let cell:educationCell = educationTableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! educationCell
print("TableView runs")
return cell
}
but I do not get my print in logs TableView runs. I do not understand what happens and why it doesn't run. Who knows, why this problem appears?
I read other answers in SO, but noone helps =/

need the return value of numberOfRowsInSection greater than 0

Just make sure you have implemented proper DataSource and Delegate for controller, number of rows is greater then 0
import UIKit
class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var items: [String] = ["We", "Heart", "Swift"]
#IBOutlet var tableView: UITableView! //hook this to your storyboard tableview
// MARK: - Controller life cycle stack
override func viewDidLoad() {
super.viewDidLoad()
//confirm table's delegate and data source programmatically
tableView.delegate = self;
tableView.dataSource = self;
}
//table view delegate and data source methods
func tableView(tableView:UITableView, numberOfRowsInSection section:Int) -> Int
{
//number of rows must be greater then 0 to get called "CellForRowAtIndex"
return self.items.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! CraditCardCell
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
print("You selected cell");
}
}

One reason could be because you modified the return type to educationCell, instdead of the standard UITableViewCell. Try changing that.

Related

Swift 3 My tableView is not populatinG?

I am wondering why is my tableview not populating? I have a tableview inside my view controller and I have tried to follow the guide however, nothing seems to show up on my tableview.
here's my code
#IBOutlet weak var weatherTableView: UITableView!
var items: [String] = ["Sunny", "Cloudy", "Rainy"]
override func viewDidLoad() {
super.viewDidLoad()
self.weatherTableView.register(UITableViewCell.self, forCellReuseIdentifier: "WeatherCell")
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = self.weatherTableView.dequeueReusableCell(withIdentifier: "WeatherCell")! as UITableViewCell
cell.textLabel?.text = self.items[indexPath.row]
return cell
}
am I missing something here?
Thanks for your help in advance
Make sure you are assigning tableview delegate and datasource throw storyboard or add below line into your viewDidLoad() of your viewcontroller (UITableViewDelegate, UITableViewDataSource)
weatherTableView.delegate = self;
weatherTableView.dataSource = self

No information is showing in my tableview inside a viewController

I have set up my table view to be filled form two arrays. I did this successfully when it was just in a tableview but not that I put it in a view controller none of the information is being displayed. I don't know what I did wrong I set up the viewController just like I did with the tableviewcontroller.
What should happen is that a row will be created and filled in with the information and continue this until all the data has been filled in.
The problem is that none of the data is showing up. I don't know what I am missing here. Any help would be appreciated.
Here is what I have;
class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var titleDate = ["Apple", "Apricot", "Banana", "Kiwi" , "Juniperberry" , "GhostBusteres"]
var descriptionDate = ["One", "Two", "Three", "4", "5", "6"]
#IBOutlet weak var myTableView: UITableView!
// MARK: - UIViewController lifecycle
override func viewDidLoad() {
super.viewDidLoad()
myTableView.editing = true
}
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titleDate.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Coupon", forIndexPath: indexPath) as! CouponTableViewCell
cell.couponTitle.text = titleDate[indexPath.row]
cell.couponDescription.text = descriptionDate[indexPath.row]
cell.couponAnother.text = "Like a bloody storm"
return cell
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return .None
}
func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
let movedObject = self.titleDate[sourceIndexPath.row]
titleDate.removeAtIndex(sourceIndexPath.row)
titleDate.insert(movedObject, atIndex: destinationIndexPath.row)
descriptionDate.removeAtIndex(sourceIndexPath.row)
descriptionDate.insert(movedObject, atIndex: destinationIndexPath.row)
NSLog("%#", "\(sourceIndexPath.row) => \(destinationIndexPath.row) \(titleDate)")
// To check for correctness enable: self.tableView.reloadData()
}
}
And I also have the cell class that links the labels to the variables and that also works.
Thank you for any help with this.
You need to set the UITableView dataSource and delegate.
When you were using the UITableViewController, the dataSource and delegate were already set.
See UITableView - Managing the Delegate and the Data Source documentation.

not calling didSelectRowAtIndexPath method in Tableview

I have embedded UITabbar in UIViewController and then I put some UITabbarItems in my UITabbar. I also created another UIViewController with UITableView embedded in it.
I have linked one of the UITabbarItem with this newly created UIViewController(with UITableView in it).
When I run the program and tap on that UITabbarItem it shows a table view but when I select any row of table, the data displaying in UITableView disappears.
I then debug the code and found that didSelectRowAtIndexPath method didn't call.
I searched on the internet and find this but cannot understand it well.
I tried by implementing both types of tableViews (UITableViewController,UIViewController with UITableView in it) but still same problem.
I am stuck here. Anyone please help me. How to get resolve this issue.
I will be very Thankful to you.
Here is my swift code
import UIKit
class DashboardViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var selectedIndexPathForCheckMark:NSIndexPath?
var items: [String] = ["We", "Heart", "Swift"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("MyCell")!UITableViewCell
cell.textLabel?.text = self.items[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You selected cell #\(indexPath.row)!")
selectedIndexPathForCheckMark = indexPath
tableView.reloadData()
}
here are its snapshots
Second UITabbarItem from right implements UITableView
Follow Steps:
1. Take A view controller and add tableview.
2. set outlet with MytabelView
3. set Datasource and delegate of tableview to ViewController
4. and put the following code in ViewController class
5. Take a custom tableview cell with name MyCell having cell identifier "MyCellid"
6. Create swift file with name MyCell, make it subclass of UITableViewCell
7. Choose custom cell and assign it class to MyCell.
I think Its done
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
#IBOutlet weak var MytableView: UITableView!
var items: [String] = ["We", "Heart", "Swift"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.MytableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "MyCellid")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.MytableView.dequeueReusableCellWithIdentifier("MyCellid")! as UITableViewCell
cell.textLabel?.text = self.items[indexPath.row]
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You selected cell #\(indexPath.row)!")
}
}

UITableView example for Swift

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;
}
}

Connect UITableView cell to another UITableView

I am stucked with my project (written in Swift)
I have a UITableView, with a string which provide ten categories in the table.
The thing that I wanna do, is to select one of these categories touching it, and open a secondTableView with other categories. And, when you press on the secondTableView, open the description of that category.
This is my code, this works to have the first UITableView, but when touching nothing happens.
Now I'd like, for example, when I click "Most important places", it open another tableView with, for example, Empire State Building, Statue of Liberty, and when touching Empire State Building, open a Description page.
import UIKit
class Categories: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tableView: UITableView!
var MainCategories: [String] = ["Most important places", "Monuments", "Nature", "Churches", "Museums", "Streets", "Zones", "Weather", "Events", "Favourites"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.MainCategories.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel?.text = self.MainCategories[indexPath.row]
return cell
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
}
}
What can I do? And in the storyboard?
Thanks you very much!
So far you have done nothing in didSelectRowAtIndexPath for the second UITableView, it would be easy for you to make use of another viewcontroller which contains the second uitableview and then a third viewcontroller for details.
But if you still want to have 2 uitableviews within same viewcontroller then please follow these steps to achieve the required result.
add another tableview and set its datasource and delegate
you have to add an if-else condition to differntiate between 2 tablieview in delegate and datasource methods, e.g. numberOfRowsInSection, cellForRowAtIndexPath, didSelectRowAtIndexPath, below is an example of the code if you use 2 uitableviews in one uiviewcontroller. you have to do this if-else for other delegate and datasource mehtos as well.
func tableView(tableView: UITableView, numberOfRowsInSection section:Int)->Int {
if tableview == self.tableView {
return self.MainCategories.count
}
else if tableView == subCategoryTableView {
return self.SubCategories.count
}
}
Hope it helps!
I have changed your code, hope this helps
import UIKit
class Categories: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tableView: UITableView!
**var selectedCategoryId = -1**
var MainCategories: [String] = ["Most important places", "Monuments", "Nature", "Churches", "Museums", "Streets", "Zones", "Weather", "Events", "Favourites"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.MainCategories.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel?.text = self.MainCategories[indexPath.row]
return cell
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
**selectedCategoryId = indexPath.row**
}
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
let vc = segue.destinationViewController as YOUR_SECOND_VIEW_CONTROLLER
vc.catId = selectedCategoryId
}
}

Resources