Unwrapping UITableView cell text - ios

I'm trying to get the text on a table view cell and then get the index of it in an array.
This is the code I'm using:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
let indexOfCellString = event.index(of: cell.textLabel!.text)
}
But I get the following errors:
value of optional type string? not unwrapped
invalid character in source file
What is going on here? What else do I need to unwrap?

There is no need to cast dequeueReusableCell to UITableViewCell since that is its return type.
cell.textLabel is optional. And then the text property of UILabel is optional.
Properly deal with optionals:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if let text = cell.textLabel?.text {
let indexOfCellString = event.index(text)
// do stuff with indexOfCellString
}
return cell
}

Related

cellForRow(at: ) returns nil

So I have this function.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! customCell
changeCellProperty(selectedIndexPath: indexPath)
return cell;
}
func changeCellProperty(selectedIndexPath: IndexPath){
print("indexpath = \(selectedIndexPath)") . // printing [0,0] and all values
let cell = self.tableView.cellForRow(at: selectedIndexPath) as! customCell
// got nil while unwrapping error in above statement.
cell.label.text = ""
// and change other properties of cell.
}
I am not able to understand the error.
When I am getting the indexpath, then why I am not able to point a particular cell and change properties accordingly.
You cannot access a cell that has not yet been added to the tableView. That is what you are trying to do here in changeCellProperty method. So, if your dequeue works, then all you would need to do is pass the dequeued cell to that method.
func changeCellProperty(cell: customCell){
cell.label.text = ""
// and change other properties of cell.
}
Your cellForRowAt method would look like this.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! customCell
changeCellProperty(cell: cell)
return cell
}
Note: class names should be UpperCamelCase. So your customCell should be named CustomCell.

array.index (of: ) not working properly

I'm trying to find a UITableViewCell text in an array. The problem is no matter what cell I'm clicking on, array.index(of:) always returns 1.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if let text = cell.textLabel?.text {
let indexOfCellString = event.index(of: text)
print (indexOfCellString!)
}
}
//here is my attempt to set the cell text:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if eventIndex.indices.contains(indexPath.row) == true {
cell.textLabel?.text = event [indexPath.row]
}
return cell
}
event is an array that i'm trying to search in and find cell's text.
and cell's text is always in an index of event. because my tableview reads the information from event array. therefore it shouldn't always return 1.
What am I doing wrong?
Never use dequeueReusableCell outside of cellForRowAt. Simply access your data from your data model.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if eventIndex.indices.contains(indexPath.row) == true {
let text = event[indexPath.row]
if let indexOfCellString = event.index(of: text) {
print("Found index: \(indexOfCellString)")
} else {
print("text not found")
}
}
}

cellForRowAt - Create and Return cell from within switch statement

I think I'm missing something fundamental to Swift, but can't find other examples of people doing what I'm trying:
Background
I have a UITableView with 2 prototype cells, with a different identifies, different features (label, image etc) and different classes.
I want the cellForRowAt function to return a different type and class of cell depending on the content in the array that holds the table data. That array is populated with struct instances, one characteristic of which identifies the type of cell that I want to represent the data.
Code Attempt
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch dataArray[indexPath.item].typeOfData {
case "Type1":
let cell = tableView.dequeueReusableCell(withIdentifier: "type1ReuseIdentifier", for: indexPath) as! type1Cell
//Set up the cell contents
return cell
case "Type2":
let cell = tableView.dequeueReusableCell(withIdentifier: "type2ReuseIdentifier", for: indexPath) as! type2Cell
//Set up the cell contents
return cell
default:
let cell = tableView.dequeueReusableCell(withIdentifier: "separatorIdentifier", for: indexPath) as! separatorCell
//Set up the cell contents
cell
}
}
What am I missing / doing wrong?
Edit:
It was missing the final return.
just do like this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let typeSection = CellType(rawValue: indexPath.row)!
switch typeSection {
case .CenterTitleCell:
return getCenterTitleCell(tableView, indexPath)
case .CenterDescriptionCell:
return getCenterDescriptionCell(tableView, indexPath)
case .CenterImageCell:
return getImageCell(tableView, indexPath)
case .FooterTitleCell:
return getFooterViewCell(tableView, indexPath)
}
}
And use another method to return the Cell Type
func getCenterTitleCell (_ tableView: UITableView, _ indexPath:IndexPath) -> CenterTitleTableViewCell {
let cell:CenterTitleTableViewCell = tableView.dequeueReusableCell(withIdentifier: String(describing: CenterTitleTableViewCell.self),
for: indexPath) as! CenterTitleTableViewCell
cell.selectionStyle = .none
return cell
}

Migration swift to swift 3 NSMutableArray

When i made the migration swift code i have this error "Type 'Any' has no subscript members" and my code is
var myArray: NSMutableArray = []
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = UITableViewCell()
if let name = self.myArray[(indexPath as NSIndexPath).row]["FirstName"] as? String{
cell.textLabel?.text = ("\(name)")
}
}
I tried many things but i do not have a answer for this problem.
First of all: Do not use NSMutableArray in Swift!
The error occurs because the compiler needs to know if the object is subscriptable by key. Using a native Swift type solves the problem.
var myArray = [[String:Any]]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = UITableViewCell() // will not work
if let name = self.myArray[indexPath.row]["FirstName"] as? String { // optional binding actually not needed
cell.textLabel?.text = name // please no string interpolation
}
return cell // mandatory!
}
Note: Consider that UITableViewCell() will not work. The recommended way are reusable cells
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
You should use
Generics
dequeueReusableCell
IndexPath instead of NSIndexPath
so here's the code
import UIKit
class Controller: UITableViewController {
var persons = [[String:String]]()
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCellID") ?? UITableViewCell(style: .default, reuseIdentifier: "MyCellID")
cell.textLabel?.text = persons[indexPath.row]["FirstName"]
return cell
}
}

unexpectedly found nil while unwrapping an Optional value in SWIFT 3.0

I am using tableview with custom cell in swift 3.0. I take a textview and give outlet of class of tabelview cell and accessing in tableview delegate method but its showing me error like unexpectedly found nil while unwrapping an Optional value
here is my code. Record is array
Chek this Screenshot. FYI I have taken A new custom class and Give Outlet to it but same problem ocuured
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return record.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
tableView.register(TableViewCell.self, forCellReuseIdentifier: "TableViewCell")
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
if let str = record.object(at: indexPath.row) as? String {
print(cell.txtview)
cell.txtview.text = str
}
return cell
}
Its perfectly working in Static cell but in custom cell it showing me error.
cell.textview is not taken from custom cell
Please help me with it
Please try with following line not sure about that:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
tableView.register(TableViewCell.self, forCellReuseIdentifier: "TableViewCell")
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
if let title = record.object(at: indexPath.row) as? String {
cell.textview.text = title
} else {
cell.textview.text = ""
}
return cell
}

Resources