Setting up a Table View Controller in Swift? - ios

I'm trying to create a table as the main screen of my app and I'm having some issues. I set up the main.storyboard correctly, but there's an override func I have that "doesn't override a superclass". The error is on the nuberOfRowsInSection override func line. Here's my code:
import UIKit
class ViewController: UITableViewController {
var candies = [Candy]()
#IBOutlet weak var editButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup
// after loading the view.
self.candies = [Candy(name: "Jolly Rancher"),Candy(name: "Snickers"),Candy(name: "Twix"),Candy(name: "Butterfinger"),Candy(name: "Milky Way")]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, nuberOfRowsInSection section: Int) -> Int {
return self.candies.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
var candy : Candy
candy = candies [indexPath.row]
cell.textLabel?.text = candy.name
}
#IBAction func editButtonPressed(sender: UIButton) {
editButton.setTitle("Save", forState: UIControlState.Normal)
}
}

Just a guess:
// this should read "numberOfRowsInSection": ~~v
override func tableView(tableView: UITableView, nuberOfRowsInSection section: Int) -> Int {
return self.candies.count
}
As far as I know, UITableViewController does not have a method with a parameter nuberOfRowsInSection, but it does have one with a parameter numberOfRowsInSection.
When dealing with something that isn't working, please start by checking your code for spelling mistakes.

You have a typing mistake. You call the method nuberOfRowsInSection. There is a 'n' missing. The method should be called numberOfRowsInSection.
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.candies.count
}
Also you have en error in your cellForRowAtIndexPath method. You have to return the cell:
return cell

Related

Tableview's delegate methods are not calling

I am trying to use tableview with delegate methods.
But it is not working.
My class:
class IsteklerTVVC: UITableViewController {
#IBOutlet var mainTable: UITableView!
let missionControl = MissionControl.sharedInstance
var yardimList:[YardimIstek] = [YardimIstek]()
override func viewDidLoad() {
super.viewDidLoad()
mainTable.delegate=self
mainTable.dataSource=self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
veriGetir()
}
func veriGetir() {
let parameters: Parameters = [
"uid": missionControl.id
]
Alamofire.request("domain.com", method: .post, parameters: parameters).responseJSON { response in
print("istek eklendi \(parameters)")
let json = JSON(response.result.value)
for (key,subJson):(String, JSON) in json {
print(subJson[0]["tarih"].string)
let blok=YardimIstek()
blok.id=0
blok.isim="Name"
blok.tarih=subJson[0]["tarih"].string!
blok.lat=subJson[0]["lat"].string!
blok.long=subJson[0]["long"].string!
self.yardimList.append(blok)
}
DispatchQueue.main.async {
self.mainTable.reloadData()
print("ok \(self.yardimList.count)")
}
}
}
let textCellIdentifier = "mainCell"
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return yardimList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: isteklerCell = tableView.dequeueReusableCell(withIdentifier: textCellIdentifier) as! isteklerCell
let row = indexPath.row
let blok=yardimList[row]
cell.setCell(blok: blok)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
}
}
class isteklerCell: UITableViewCell {
#IBOutlet weak var isimSoyisim: UILabel!
#IBOutlet weak var zaman: UILabel!
func setCell(blok: YardimIstek) {
isimSoyisim.text=blok.isim
zaman.text=blok.tarih
}
}
The problem is, no delegate methods are getting called. I think there is a problem with names. Because when I was using Swift 2, I used the tableview's outlet name as "tableView" and it was working well. Now Swift 3 is not allowing that naming.
So my tableview is looking empty even there is data in yardimList dictionary.
How can I resolve this?
Your delegate function signatures are wrong. They were updated with swift 3:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
Two things to check:
First one is do you need the mainTable property? UITableViewControllers comes with a UITableView property called tableView. If you don't need 'mainTable', you can just replace it with tableView.
Second, if you do need mainTable, then you need to make sure you connected the #IBOutlet to the UITableView you want to use.

How to put string from array into variable using UITableView Swift

I want to put the string from whichever cell is chosen (part of the arrat basicPhrases) into a variable (selectedBPhrase) then I want to perform the segue BasicPhrases2Phrase and have it display the string by itself. How do I do that? I'm pretty sure it has something to do with using didSelectRowAtIndexPath but I'm not sure.
This is my code:
import UIKit
class BasicPhrases: UITableViewController {
let basicPhrases = ["Hello.","Goodbye.","Yes.","No.","I don't understand.","Please?","Thank you.","I don't know."]
var selectedBPhrase = ""
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return basicPhrases.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")!
cell.textLabel?.text = basicPhrases[indexPath.row]
return cell
}
I think it's in here but not sure.
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("BasicPhrases2Phrase", sender: self)
}
}
Thanks for any help in advance.
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
selectedBPhrase = basicPhrases[indexPath.row]
performSegueWithIdentifier("BasicPhrases2Phrase", sender: self)
}
You need to get UIViewTableCell from indexPath, as in cellForRowAtIndexPath, as in didSelectRowAtIndexPath.

UITableViewController swift different sizes of height with images

I have an UITableViewController that has 2 cells and when I put a photo in it, it comes out to be the same size. The coding I put in the ViewController.swift is
import UIKit
class TableViewController: UITableViewController {
var imageArray = ["1.png","2.png"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell!
let imageView = cell.viewWithTag(2) as! UIImageView
imageView.image = UIImage(named: imageArray[indexPath.row])
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return imageArray.count
}
}
I'm not sure of what you are looking for? If what you want is two cells with differents height, you should try to override
override func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
}
in your delegate.

Swift model not get updated from table cell

I have a tableviewcontoller, it retrieves the data and stores in model objects. The model object is assigned to table cells. when i make a change in table cell text box, the changes are not get updated to model. Is anything wrong in this code? if this is not right approach, please let know how to get the changes in table row.
class myTable: UITableViewController , UITableViewDelegate, UITableViewDataSource{
var models = [Customer]()
override func viewDidLoad() {
super.viewDidLoad()
self.generateUpdateModels()
self.tableView.dataSource = self
self.tableView.delegate = self
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("rowIdentifier", forIndexPath: indexPath) as! TextInputLabelTableViewCell
cell.first.text = models[indexPath.row].first //label
cell.last.text = models[indexPath.row].last //label
cell.status.text = models[indexPath.row].status //textbox
return cell
}
func generateUpdateModels(){
//update models[]
}
#IBAction func done(sender: AnyObject) {
//look into models for changes....
// don't see the changes
self.performSegueWithIdentifier("final", sender: self)
}

ViewController does not confirm to protocol 'UITableViewDataSource'

This question was asked multiple times.
http://stackoverflow.com/questions/25581780/type-viewcontroller-does-not-confirm-to-protocol-uitableviewdatasource
and I did tried the solutions provided over there but still I am not able to get away with this error. Code to UITableView is below
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
{
#IBOutlet var tableView: UITableView!
var data: [String] = ["one","two","three","four"]
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.data.count;
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath!)
{
println("You clicked cell number #\(indexPath.row)!")
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel?.text = self.data[indexPath.row]
return cell
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Please tell what mistake am I doing here.
Try this just remove both the function numberOfRowsInSection and cellForRowAtIndexPath and again add this function like :
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return self.data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel?.text = self.data[indexPath.row]
return cell
}
This is works for me.
The following code didn't work for me on iOS 8.1. in XCode 6.1.1. This code works:
import UIKit
class ViewController : UIViewController,UITableViewDelegate,UITableViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
//currently only a testing number
return 25
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
var cell:UITableViewCell=UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "mycell")
cell.textLabel?.text = "row#\(indexPath.row)"
cell.detailTextLabel?.text = "subtitle#\(indexPath.row)"
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Please confirm all tableview required methods before the last }. Like
class ViewController:UIViewController,UITableViewDataSource,UITableViewDelegate {
var data: [String] = ["one","two","three","four"]
override func viewDidLoad() {
super.viewDidLoad()
self.loadTableView()
// 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.
}
func loadTableView() {
var tableObj:UITableView=UITableView()
tableObj=UITableView(frame: UIScreen.mainScreen().bounds, style: UITableViewStyle.Plain)
tableObj.delegate=self;
tableObj.dataSource=self;
self.view.addSubview(tableObj)
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Section (section)"
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell=UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "mycell")
var nameLabel:UILabel = UILabel(frame: CGRect(x: 50,y: 5,width: 200,height: 30))
nameLabel.text="Title\(indexPath.row)"
nameLabel.textColor=UIColor.brownColor()
nameLabel.font=UIFont.boldSystemFontOfSize(15)
nameLabel.textAlignment=NSTextAlignment.Left
cell.contentView.addSubview(nameLabel)
var imageView:UIImageView=UIImageView(frame: CGRect(x: 5,y: 2,width: 40,height: 40))
imageView.backgroundColor=UIColor.purpleColor()
imageView.layer.masksToBounds=true
imageView.layer.cornerRadius=imageView.frame.width/2
cell.contentView.addSubview(imageView)
return cell
}
}

Resources