Xcode error: 'Cannot assign to value: function call returns immutable value' in table views - swift2

I am confused as I am defining content of rows in a table view by a dictionary, but when ever I try to add it, it shows me an error.
var places = [[String: Any]]()
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
if places.count == 0 {
places.append(["name":"Taj Mahal", "lat": "27.175277", "lon": "78.042128"])
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = places[indexPath.row]["name"]
return cell
}
the error is in the part where I define:
cell.textlabel?.text = places[indexPath.row]["name"]

It should be:
places[indexPath.row]["name"] as! String
As the type is Any and you need to specify it as String, since label expects Strings.

Related

How to store a hidden string with a UITableViewCell?

I want to attach information (a string) to each UITableViewCell when populating TableView with UITableViewCells. I don't want it to be visible- I just need to access this string when the row/cell is selected. What is the best way to do this?
Your best choice is probably to subclass UITableViewCell and add a string property. This can then be assigned either as a constant, or when setting up your cells in cellForRowAtIndexPath:.
class CustomCell: UITableViewCell {
var customString = "Default"
}
--------
func cellForRow(atIndexPath indexPath: IndexPath) -> UITableViewCell {
guard let cell: CustomCell = tableView.dequeueReusableCell(withReuseIdentifier: "identifier", indexPath: indexPath) as? CustomCell else {
return UITableViewCell()
}
cell.customString = "String"
return cell
}
func didSelectRow(atIndexPath indexPath: IndexPath) {
guard let cell: CustomCell = tableView.cellForRow(atIndexPath: indexPath) as? CustomCell else {
return
}
let stringFromCell = cell.customString
}
The above has not been compiled, so may not work word for word, but you get the principle.
Add a property selected to your model.
In cellForRow show/hide the string depending on the state of selected.
In didSelectRow toggle selected in the model and reload the row.

Pass information from Parse to the TableiewController

I have an issue when I'm trying to pass the information from the database from Parse to my TableViewController. I think that is the way I'm calling to the name and password.
When I push the View Users button the app crash.
I put my git if you need more information. https://github.com/emmanuelcu/ParseProject.git
class TableViewController: UITableViewController{
var dataParse:NSMutableArray = NSMutableArray()
var count:Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
//PFQuery
let query = PFQuery(className: "LoginCredentials")
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]? , error: NSError?) -> Void in
if(error == nil){
print("The current number of users is \(objects!.count)")
self.count = objects!.count
self.tableView.reloadData()
} else {
print("Error")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
//return self.dataParse.count
return self.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "CellData"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! TableViewCell
// Configure the cell...
cell.password.text = dataParse[indexPath.row]["name"] as? String
cell.name.text = dataParse[indexPath.row]["user"] as? String
print("Error")
return cell
}
When you run your query you never assign your objects to your data source, only the number of objects that you receive. Also you're force unwrapping that count without checking if objects has a count, which is possible even without an error.
It works like this dataParse array is empty you should populate it, or should disable view users button when it is empty etc.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "CellData"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! TableViewCell
// Configure the cell...
if dataParse.count > indexPath.row {
cell.password.text = dataParse[indexPath.row]["name"] as? String
cell.name.text = dataParse[indexPath.row]["user"] as? String
}
print("Error")
return cell
}

Swift 1.2 - List type undeclared

In my TableViewController i have this line of code
override func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
In this block i try to get a list of objects
let list = frc.objectAtIndexPath(indexPath) as! List
But i get this warning:
Use of undeclared type "List"
Anybody knows how to deal with it?
This is the full code:
var frc: NSFetchedResultsController = NSFetchedResultsController()
override func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell",
forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
let list = frc.objectAtIndexPath(indexPath) as! list
cell.textLabel?.text = list.name
cell.detailTextLabel?.text = list.url
return cell
}
Any help is welcome!!
Greetings and Thanks
In the tutorial, Jason creates an entity called "List" in his Data Model file and then creates a class called List.
The following link starts the video just after he creates this file.
https://youtu.be/GeM7Zw12wbM?t=5m30s
You may have named your entity differently.
I named mine Record, since I'm storing records.
So my code will look like the following:
var frc: NSFetchedResultsController = NSFetchedResultsController()
override func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell",
forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
// ALL occurrences of "list" are instead "record"
// ALL occurrences of "List" are instead "Record"
let record = frc.objectAtIndexPath(indexPath) as! Record
cell.textLabel?.text = record.name
cell.detailTextLabel?.text = record.url
return cell
}

Registering a Nib

I would like to set the values of detail labels in the View Controller file using an array with index path.row .
In a previous post:
[link][1]
someone helpfully suggested I use
var nib = UINib(nibName: "YourCellSubclass", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "cell")
however I'm new to using this and came across an error:
Cannot invoke registerNib with an argument list of type 'UINib, forCellReuseIdentifier: 'String'
My best guess would be, instead of this:
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
Should be:
var cell: YourSubClass = self.tableView.dequeueReusableCellWithIdentifier("cell") as YourSubClass
This compiles in Xcode 7:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! MyCellSubclass
return cell
}
If you have multiple kinds of cells, you can go with:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let aCell = table.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
if let myCell = aCell as? MyCellSubclass {
return myCell
}
return aCell
}

AnyObject is not convertible to UITableViewCell

I'm using the Beginning Swift Programming book by AppCoda and I can't seem to figure out what is wrong with this block of code.
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
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.
}
var restaurantNames = ["Cafe Deadend", "Homei", "Teakha", "CafeLoisl", "Petite Oyster", "For Kee Restaurant", "Po's Atelier", "Bourke Street Bakery", "Haigh’s Chocolate", "Palomino Espresso", "Upstate", "Traif", "Graham Avenue Meats And Deli", "Waffle & Wolf", "Five Leaves", "Cafe Lore", "Confessional", "Barrafina", "Donostia", "Royal Oak", "CASK Pub and Kitchen"]
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return restaurantNames.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->
UITableViewCell {
let cellIdentifier = "Cell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as UITableViewCell
// Configure the cell...
cell.textLabel.text = restaurantNames[indexPath.row]
return cell
}
}
This line is throw a 'AnyObject is not convertible to 'UITableViewCell'
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as UITableViewCell
I'm really new to Swift and iOS programming in general so any help would be appreciated.
You need to change as to as!
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
Also make sure that you have added a prototype cell to your storyboard with the reusable string name "Cell"
//MARK: Tableview
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
{
return tabledata.count
}
func tableView(tableView: UITableView!,
cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
let cell:UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:"Cell")
cell.textLabel?.text = tabledata[indexPath.row]
return cell
}
I have used this code for tableview....You can change this according to your need.Even I'm new in swift or else I would've correct your code.

Resources