Reputation: 877
This code reads from a json file and returns the "name" value in all cells, this is working fine, but when I select the value it keeps returning nill, I want to get the value. I tried some other solutions in other questions because they are in Objective C and this is swift, I tried though and didn't work at all. All I want is the value inside the cell. Also I want to pass the value of the "id" as well, which is data["id"] of the selected cell, is that possible.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ImageCell", forIndexPath: indexPath) as UITableViewCell //1
let data = datas[indexPath.row]
if let captionLabel = cell.viewWithTag(100) as? UILabel {
if let caption = data["name"].string{
captionLabel.text = caption
}
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let indexPath = self.tableView.indexPathForSelectedRow();
let currentCell = self.tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;
println(currentCell.textLabel!.text)
self.viewofloc.hidden = true
}
Upvotes: 1
Views: 2807
Reputation: 7260
Method tableView:didSelectRowAtIndexPath: provides an index path for your selected cell. No need to recalculate it with self.tableView.indexPathForSelectedRow.
Try to edit your tableView:didSelectRowAtIndexPath:
with this:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let currentCell = self.tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell!;
}
I had tried this with new Xcode project (Master-Detail Application) and got a cell.
Upvotes: 2
Reputation: 9414
Get rid of the tags and just create a simple UITableViewCell
subclass then access the UILabel directly. You'll see expanding your cell will get cumbersome using tags.
Also, your indexPath is already supplied in didSelectRowAtIndexPath
so grab your cell using the supplied tableView
and indexPath
.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ImageCell", forIndexPath: indexPath) as? ImageCell
let data = datas[indexPath.row]
if let caption = data["name"] as? String {
cell.labelCaption.text = caption
}
return cell!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as! ImageCell;
println(currentCell.textLabel!.text)
self.viewofloc.hidden = true
}
class ImageCell: UITableViewCell {
@IBOutlet weak var labelCaption: UILabel!
}
Upvotes: 1