swift UITableViewDataSource xcode 6.1 - uitableview

I'm trying to use UITableViewDataSource in my application.But when I add to UITableViewDataSource to viewControllerClass
This is my code
class SecondViewController: UIViewController,UITableViewDataSource{
And there is error what I am getting
'SecondViewController' does not conform to protocol 'UITableViewDataSource'
self.messageTableView!.registerNib(UINib(nibName: "MessageCell", bundle: nil), forCellReuseIdentifier: "MessageCell")
self.messageTableView!.rowHeight = UITableViewAutomaticDimension;
self.messageTableView!.estimatedRowHeight = 44.0;
self.messageTableView!.keyboardDismissMode = .Interactive
self.view.addSubview(self.messageTableView!)

I reconstructed your code except for the custom message cell and it compiled. I noticed that the improper use of ! in the two required functions for the UITableView will give that message. If you click on the error message (marked in red) it will display additional error messages in the lines causing the problem. Start by removing the ! and sometimes the compile will provide a correctionI also saw on another stack overflow that there was change between 6 and 6.1. I am using 6.1. ([iOS : 'MyViewController' does not conform to protocol 'UITableViewDataSource')
class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var messages = ["A", "B", "C"]
#IBOutlet var tableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
tableView!.dataSource = self
tableView!.delegate = self
self.tableView!.registerNib(UINib(nibName: "MessageCell", bundle: nil), forCellReuseIdentifier: "MessageCell")
self.tableView!.rowHeight = UITableViewAutomaticDimension;
self.tableView!.estimatedRowHeight = 44.0;
self.tableView!.keyboardDismissMode = .Interactive
self.view.addSubview(self.tableView!)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return messages.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell:UITableViewCell=tableView.dequeueReusableCellWithIdentifier("MessageCell") as UITableViewCell
var msg=self.messages[indexPath.row]
//cell.configureWithMessage(msg)
return cell
}
}

You have to implement the non optional functions of the protocol, which are:
tableView:numberOfRowsInSection
tableView:cellForRowAtIndexPath

Related

why aren't my UITableViewDataSource functions getting called?

As I run the code I am successfully feeding JSON data into my application at the rendering of this associated UIView. I have a tableView adequately linked to this file, when I run the application I see the tableview itself. BUT none of the 3 datasource functions are automatically getting called - the 'wtf' print statement, after 2 hours of playing with this, will.not.print.
am I missing something? This code is identical to all other tableviewdatasource code I've written and this simply won't work or render the JSON data I am supplying it with
does anyone have thoughts or suggestions? Thanks!
import UIKit
class ChooseUserViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var users: [BackendlessUser] = []
override func viewDidLoad() {
super.viewDidLoad()
loadUsers()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("wtf")
return users.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("chooseCell", forIndexPath: indexPath)
let user = users[indexPath.row]
print("wtf!")
cell.textLabel?.text = user.email
return cell
}
}
You have tableview with datasource and delegate connected with view controller in storyboard(Interface Builder).
In case you're forgotten to set the dataSource and delegate in your Storyboard using Ctrl+Drag you need to specify in your viewDidLoad that you're the dataSource and delegate like in the following way:
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
loadUsers()
}
I hope this help you.
The Answer: I had not connected the delegate and the datasource of my table object to the view controller - OOPS! I feel silly but that was clearly my issue

iOS Swift 2.0: Use of unsolved identifier 'UITableviewCell'

I was following a coding tutorial of making a simple app, everything looked and worked okay at first but after a while I ran into an error says:
use of unresolved identifier 'UITableViewCell'.
The tutorial's code worked fine in its video and I wrote the exact same code however it was an error on my computer. I guess it's the matter of different versions of Xcode.
Here is my code:
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tableView.dataSource = self
self.tableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 6
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
**let cell = UITableviewCell()**
*//Where the error message is at. //*
return cell
}
}
The error message is at the line:
let cell = UITableViewCell()
I cannot comment on the answer posted by Stefan Salatic but you have to indeed use dequeable cells but to add to that, you should not forget to set the identifier in the main.storyboard to the CellIdentifier you used to create dequeable cell.
let cell = tableView.dequeueReusableCellWithIdentifier("Identifier", forIndexPath: indexPath) as UITableViewCell
In the storyboard go to the TableViewController -> Attribute Inspector -> Identifier and set it to:
Identifier
If you have an array of data you can fill the cell using:
cell!.textLabel?.text = data[indexPath.row]
You should dequeue UITableViewCells. Something like this
let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
You want to reuse cells, not create a new one each time. This is the preferred way of doing it.

How to connect dataSource and delegate with code - iOS Swift

I'm trying to have a better understanding on how the dataSource and delegate outlets get connected to the UITableView under the hood when you do the connection through the UI in Xcode by dragging and dropping to the viewController icon.
I found this thread but I think I'm missing something because I cannot make it work.
Here is the code I currently have that works fine by connecting the outlets through XCode (by drag and dropping).
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var hobbies:[String] = ["Computers", "Photography", "Cars", "Reading", "Learning New Things"]
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return hobbies.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = hobbies[indexPath.row]
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I tried removing the outlet connections made by XCode, created an outlet for the tableView (myTable) and added the following code in the viewDidLoad method but it doesn't work, no error it just doesn't load the data.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
myTable.delegate = self
myTable.dataSource = self
}
Can someone describe the steps needed to do this connection with code?
Just for reference here are the steps needed to do your connection programmatically.
1.- Create outlet for tableView
#IBOutlet weak var myTable: UITableView!
2.- Assign delegate and dataSource in the viewDidLoad method.
myTable.delegate = self
myTable.dataSource = self
3.- DONE
There are a couple of ways to do it.
1. The simplest one is by dragging and dropping:
In your main.storyboard select your TableView;
Press your Control button;
Click and drag the mouse from your TableView to your ViewController's icon and drop it;
Then select dataSource and delegate as shown on the image above.
2. The other way is by coding:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
}
PS: Make sure not to forget connecting your tableView outlet to your code by dragging and dropping it into your ViewController class.
PPS: It'll also ask you to implement the following methods into your class so that your tableView works properly:
numberOfRowsInSection
cellForRowAtIndexPath
For those who don't have them yet, you'll see Xcode complaining about it.

cellForRowAtIndexPath is not being called from custom class

I'm using Xcode 7.0, Swift 2
I'm basically trying to create a custom class that will build a UITable, then in the ViewController I make a new object of the table and load it into self.view;
The problem I'm having is that the function func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell isn't being called at all from within the custom class. I've been looking for a solution for 3 days now and I've tried rebuilding the App and code several times with no luck.
Please note, if I use the same code (that is everything required to build the table; excluding init functions, etc) in the ViewController.swift file, it works fine.
I know the problem is with the cellForRowAtIndexPath function because it will not print out the statement I set in that block of code when it runs. All other functions are called, but for some reason this isn't being called. Not sure if I overlooked something here. Any help would be appreciated. Thanks in advance.
class sideTest: NSObject, UITableViewDelegate, UITableViewDataSource {
let tesTable: UITableView = UITableView()
var items: [String]?
var mView: UIView = UIView()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("The number of rows is: \(self.items!.count)")
return self.items!.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print("\nLets create some cells.")
let sCell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell!
sCell.textLabel?.text = self.items![indexPath.row]
sCell.textLabel?.textColor = UIColor.darkTextColor()
return sCell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You selected cell #\(indexPath.row)!")
}
func tblSetup() {
self.tesTable.frame = CGRectMake(0, 0, 320, mView.bounds.height)
self.tesTable.delegate = self
self.tesTable.dataSource = self
self.tesTable.backgroundColor = UIColor.cyanColor()
// load cells
self.tesTable.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
self.tesTable.reloadData()
print("Currenlty in tblSetup.\nCurrent rows is: \(self.items!.count)")
}
//Init
override init() {
super.init()
self.items = nil
self.tblSetup()
}
init(sourceView: UIView , itemListAsArrayString: [String]) {
super.init()
self.items = itemListAsArrayString
self.mView = sourceView
self.tblSetup()
}
}
Here is the code from ViewController.swift; Please do note that the table gets built, but the cells do not populate, even if I manually enter cell info by doing: sCell.textLabel?.text = "test cell"
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let myTable: sideTest = sideTest(sourceView: self.view, itemListAsArrayString: ["Cell 1", "Cell 2", "Cell 3"])
self.view.addSubview(myTable.tesTable)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Again, any help is greatly appreciated. Thanks.
Your view controller don't have a strong reference to your sideTest var.
Once your view did load finished,your sideTest is nil.Although you have a tableview(by add subview), but you no longer have a data source.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {}
is called after view did load. That cause the problem.
change your view controller to:
var tb :sideTest?
override func viewDidLoad() {
super.viewDidLoad()
let myTable: sideTest = sideTest(sourceView: self.view, itemListAsArrayString: ["Cell 1", "Cell 2", "Cell 3"])
print(myTable.tesTable.frame)
tb=myTable
self.view.addSubview(myTable.tesTable)
}
change your cellforrowatindexpath to:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print("create cells")
var cell :UITableViewCell?
if let sCell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell"){
cell=sCell
}else{
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
}
cell!.textLabel?.text = self.items![indexPath.row]
cell!.textLabel?.textColor = UIColor.darkTextColor()
return cell!
}
this will fix most of the problems.
Your code:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let myTable: sideTest = sideTest(sourceView: self.view, itemListAsArrayString: ["Cell 1", "Cell 2", "Cell 3"])
self.view.addSubview(myTable.tesTable)
}
I would think that the myTable variable goes out of scope and is released when viewDidLoad finishes, so there is no data source or delegate after that. Did you verify that the self.view.addSubview(myTable.tesTable) retains it? Try moving declaration of myTable outside of the function level (to property level) or add a diagnostic print to deinit..

Swift Custom UITableViewCell not displaying data

I am new to Swift, and iOS development in general. I am attempting to create a custom UITableViewCell. I have created the cell in my main storyboard on top of a UITableView that is inside a UIViewController. When I loaded one of the default cells, I was able to populate it with data. However, now that I am using a custom cell, I cannot get any data to appear in the table. I have gone through all kinds of tutorials and questions posted on the internet, but I can't figure out why it is not working. Any help would be appreciated.
Here is my code for the UIViewController that the tableview resides in.
import UIKit
class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tblView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//self.tblView.registerClass(UITableViewCell.self, forCellReuseIdentifier : "Cell")
self.tblView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier : "Cell")
tblView!.delegate = self
tblView!.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataMgr.data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : CustomTableViewCell = self.tblView.dequeueReusableCellWithIdentifier("Cell", forIndexPath : indexPath) as! CustomTableViewCell
var values = dataMgr.data[indexPath.row]
cell.newTotalLabel?.text = "\(values.newTotal)"
cell.winLoseValueLabel?.text = "\(values.newTotal - values.currentTotal)"
cell.dateLabel?.text = "5/17/2015"
return cell
}
}
I have stepped through the program where it is assigning values to the cell variables. The variable 'values' is being populated with data, but when stepping over the assignment lines to the cell variables, I found that they are never assigned. They all remain nil.
When you make a custom cell in the storyboard, don't register the class (or anything else). Just be sure to give the cell the same identifier in the storyboard that you pass to dequeueReusableCellWithIdentifier:forIndexPath:.

Resources