Can't get UITableViewAutomaticDimension to work properly - swift2

I have a fairly standard UITableView that populates via custom cell. That cell is simply an image and a label at the moment. I cannot, for the life of me, get it to resize on it's own.
When I include UITableViewAutomaticDimension, I lose the ability to populate my data in addition to incorrect layouts.
Without UITableViewAutomaticDimension, the data is displayed properly.
I am using SnapKit to handle constraints and Meteor/SwiftDDP to handle the data, but there is another UITableView in the project that seems to be working properly
ViewController
class CommentViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var commentTable:UITableView!
var comments:MeteorCollection<Comment>!
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
comments = MeteorCollection<Comment>(name: "comments")
createView()
Meteor.subscribe("postsComments", params: [["postId": self.source!.id!]]) {}
}
func createView() {
let contentTableView = UITableView(frame: content.frame)
content.addSubview(contentTableView)
contentTableView.backgroundColor = UIColor.clearColor()
self.commentTable = contentTableView
contentTableView.delegate = self
contentTableView.dataSource = self
contentTableView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(content)
make.left.equalTo(content)
make.right.equalTo(content)
make.height.equalTo(content).inset(65)
}
contentTableView.rowHeight = UITableViewAutomaticDimension
contentTableView.estimatedRowHeight = 350
}
}
CommentTableViewDelegate.swift
import UIKit
extension CommentViewController {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.comments.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(CommentTableViewCell.reuseIdentifier, forIndexPath: indexPath) as UITableViewCell
cell.setNeedsUpdateConstraints()
cell.updateConstraintsIfNeeded()
if let card = cell as? CommentTableViewCell {
let item = self.comments.sorted[indexPath.row]
card.populate(item)
}
return CommentTableViewCell()
}
func reloadTableView() {
self.commentTable.reloadData()
}
}
An example of my garbled mess when not using UITableViewAutomaticDimension
An example of my garbled mess when using UITableViewAutomaticDimension

It might be due to improper constraint within cell. Please add constraint properly in table view cell and set these two properties of UILable from Attributes inspector section of storyboard:
lines to 0
Line break to word wrap
or you can also set these properties from code:
self.lblxyz.numberOfLines = 0
self.lblxyz.lineBreakMode = .byWordWrapping
Note - Do not fix the height of UILable.
Hope it will help you... :)

I'm not sure if it works but, I've been through the same problem recently, and i fixed it by changing the estimatedRowHeight .
Can you please try once with:-
contentTableView.estimatedRowHeight = 350
to, contentTableView.estimatedRowHeight = 160

Related

Why the cell height is not changing on tapping the button once. It is working only when I tap the button twice

Click Here To see the UI of my app
Here In the image you can see the ui.
--> There is a tableView & a button on the main view.
--> I have taken a custom tableViewCell class
In the cell I have taken a UIView
Constraints Added To That View are:
centre horizontally, height, width, top & bottom constraint
I have added a outlet of the height constraint to the TVCell class
--> I have taken a button and added a event handler to it
--> Button Event handler:
In button event handler I am just changing the height of the view in the first cell and reloading the cell.
Now the problem is that height of the cell is changing when I tap on the button. But its happening only when I tap one the button twice. So I want to know why is it happening. Here I am adding my code below.
I have one solution for this problem which you can see after you see after the code of the ViewController & TableViewCell Class
VIEW CONTROLLER CLASS
import UIKit
class ViewController: UIViewController,UITableViewDataSource{
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.separatorColor = UIColor.black
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
return cell
}
#IBAction func buttonAction(_ sender: Any) {
let indexPath = IndexPath(row: 0, section: 0)
let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
if cell.viewHeightConstraint.constant == 75 {
cell.viewHeightConstraint.constant = 10
}
else{
cell.viewHeightConstraint.constant = 75
}
tableView.reloadRows(at: [indexPath] , with: UITableView.RowAnimation.automatic)
}
}
TABLEVIEWCELL CLASS
import UIKit
class TableViewCell: UITableViewCell {
#IBOutlet weak var viewHeightConstraint: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
//Setting View Height To 75
viewHeightConstraint.constant = 75
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
You can get this source code from this link below
https://github.com/himansudev/tableViewIssue_15_4_20_1.git
Now I have a solution for this problem but I believe its not a proper solution. So what I have done is as shown below
1) I have modified the button event handler, see below is the modified code. Please refer to the above code to identify the changes that I have made to this event handler
#IBAction func buttonAction(_ sender: Any) {
let indexPath = IndexPath(row: 0, section: 0)
tableView.reloadRows(at: [indexPath] , with: UITableView.RowAnimation.automatic)
}
2) Secondly I have added this extra piece of code , see below
override func viewDidLayoutSubviews() {
print("viewDidLayoutSubviews")
let indexPath = IndexPath(row: 0, section: 0)
let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
if cell.viewHeightConstraint.constant == 75 {
cell.viewHeightConstraint.constant = 10
}
else{
cell.viewHeightConstraint.constant = 75
}
}
Find the source code after changes below
https://github.com/himansudev/tableViewSolution_15_4_20_1.git
Now after doing these two changes it is working (but sometimes it doesn't work when I tap on the button rapidly many times) but the problem is the viewDidLayoutSubviews() is not getting called but when I comment it than the cell is not working as expected .
SO I want to know why is it behaving that way???
First of all you need to add also the UITableViewDelegate to your ViewController and a var like this:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var cellHeight: CGFloat = 75
and the heightForRow function which will return the right Height:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return cellHeight
}
Then on your button action:
#IBAction func buttonAction(_ sender: Any) {
if cellHeight == 75 {
cellHeight = 10
}
else{
cellHeight = 75
}
tableView.reloadData()
}
Also remove the constraint viewHeightConstraint because you do not need it.

Xcode 10.3 (10G8) breaks app with compilation mode = "Whole Module"

I pushed my version 7.6 of my iOS app to the App Store and noticed that the app suddenly contained many bugs (strange behaviours) that did not show up during debugging.
Since the app worked perfectly in xCode 9.x I suspect strongly that the issues started happening with Xcode 10.3.
I am using Swift 4.2 (conversion of Swift 5 is for next update)
After investigating for many hours I located the issue: when Compilation mode = "whole module" the bugs appear and when set to "incremental" the disappear. In debug mode (when app is run out of Xcode) the Compilation mode is set to "incremental" for release its "whole module" (this is the standard configuration when you create a new project in Xcode 10.x I suspect) this explains why we did not see the issues during debug testing.
Also note that changing to legacy build system did not solve the issues. Only setting Compilation mode = "incremental" solved the issues.
Analysis:
I tracked the issue to the fact that for all my TableViews the delegate was not being called. 
I have the following simple hierarchy :
Code of the ViewTableRoot:
class ViewTableRoot : UITableView, UITableViewDelegate, UITableViewDataSource {
var didScrollToOffset : ( (CGFloat) -> Void )?
var didEndScrolling : ( (CGFloat) -> Void )?
var didChangeEditing : ( ( ) -> Void )?
//MARK: lifecycle
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
setup();
}
func setup() {
//set the corner radius of the layer so that the sliding of the cells underneath the rounded headers does not show up
layer.cornerRadius = 5
//setup myself as delegate and data source
delegate = self
dataSource = self
}
deinit {
let className = String(describing: self)
log.debug("**********\(className)")
}
//MARK: - public API
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
didChangeEditing?()
}
//MARK: - scrollview delegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//because we are also getting events when swiping on the cells, we need to see the difference between
//swipig on the cell and swiping in the "actual" table => we do this by checking the frame size
guard scrollView.frame == frame else { return }
didScrollToOffset?(scrollView.contentOffset.y)
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
//because we are also getting events when swiping on the cells, we need to see the difference between
//swipig on the cell and swiping in the "actual" table => we do this by checking the frame size
guard scrollView.frame == frame else { return }
if !decelerate {
didEndScrolling?(scrollView.contentOffset.y)
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
//because we are also getting events when swiping on the cells, we need to see the difference between
//swipig on the cell and swiping in the "actual" table => we do this by checking the frame size
guard scrollView.frame == frame else { return }
didEndScrolling?(contentOffset.y)
}
//MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
preconditionFailure("Must be implemented by derrived class")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
preconditionFailure("Must be implemented by derrived class")
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
preconditionFailure("Must be implemented by derrived class")
}
//MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
Code of the ViewTableSettings:
class ViewTableSettings : ViewTableRoot {
var settings : [[Setting]]? {
didSet {
reloadData()
}
}
var didPressSetting : ((Setting, CGRect) -> (Void))?
//MARK: lifecycle
override func setup() {
super.setup()
log.debug("delegate : \(delegate)")
//register xibs
register(CellTableSetting.nib, forCellReuseIdentifier: CellTableSetting.reuseIdentifier)
}
//MARK: - UITableView
override func numberOfSections(in tableView: UITableView) -> Int {
let count = settings?.count ?? 0
log.debug("count: \(count)")
log.debug("delegate : \(delegate)")
return count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let count = settings?[section].count ?? 0
log.debug("count: \(count)")
log.debug("delegate : \(delegate)")
return count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
log.debug("delegate : \(delegate)")
//ask for a new cell
let cell = tableView.dequeueReusableCell(withIdentifier: CellTableSetting.reuseIdentifier, for: indexPath) as! CellTableSetting
guard let setting = settings?[indexPath.section][indexPath.row] else {
preconditionFailure("Asking CellTableSetting but no Setting model defined")
}
//load up!
cell.setting = setting
cell.lastCell = indexPath.section != numberOfSections - 1 ? false : indexPath.row == (numberOfRows(inSection:indexPath.section) - 1)
//return cell to use
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
log.debug("-")
return CellTableSetting.height
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
log.debug("-")
tableView.deselectRow(at:indexPath, animated: true)
guard let setting = settings?[indexPath.section][indexPath.row] else {
return
}
didPressSetting?(setting,rectForRow(at: indexPath))
}
func tableView(_: UITableView, viewForFooterInSection: Int) -> UIView? {
log.debug("-")
guard viewForFooterInSection < (numberOfSections-1) else {
let version = UILabel()
version.text = UIApplication.AppVersionAndBuildPrettyPrint
version.font = UIFont.defaultBoldFont(size: 12)
version.textColor = PaintCode.mainLightGray_a50
version.textAlignment = .center
return version
}
let v = UIView()
v.backgroundColor = PaintCode.mainLightGray_a50
return v
}
func tableView(_: UITableView, heightForFooterInSection: Int) -> CGFloat {
log.debug("-")
return heightForFooterInSection < (numberOfSections-1) ? 5 : 40
}
}
as you can see the ViewTableRoot declares compliance to the UITableViewDelegate (also to UITableViewDataSource but that is besides the issue for now)
the delegate is actually assigned to self in the ViewTableRoot but the actual delegate functions are implemented in the derived ViewTableSettings(again this worked perfectly in Xcode 9.x)
when compilation mode = "Whole Module" these delegate functions are not being call => this is the bug
when set to "incremental" these delegate functions are called just fine!
Additional tests I have done to get more insight in the issue:
switching to the "legacy build system" (via Xcode/file/project settings) does not solve the issue; as long as the Whole Module is enabled the issue remains
when I create empty delegate functions in the ViewTableRoot and override them in the ViewTableSettings it does work :-o
I did verify in ViewTableSettings that the delegate was indeed set to an instance of ViewTableSettings and not ViewTableRoot (in which case there would not be any delegate functions implemented)
My thoughts
I get the feeling that I stumbled upon a bug in the (new?) build system?
Anybody else run into similar issues?
Yes, I have the same issue as you. When the Compilation Mode is "Whole Module", the Collectionview controllers are messed up but not the Tableview controllers. result on simulator device. Maybe you can try to use UITableViewController directly rather than conform TableView protocol.
Installed the latest Xcode 11.4 (11E146) and the problem seams to be resolved in this version. I have re-enabled the whole module optimization and everything seams to be working as expected. So... turns out that it was a bug XCdoe!

swift3 extension functions not called

I'm a high school student working on an app in Xcode 8 using Swift 3. I am trying to create a way to create a table view with collapsible sections. I am trying to create a way to have my code create a view that pushes all of the data into organized sections. Im trying to have my data displayed through using an extension. Even when I have a breakpoint after the extension it never reaches that point.
Edit: The rest of the app is built within the Main.storyboard, however (as you can see), this tableViewController is built entirely within code.
I can create a segue to the WeaponSelectVC however, none of the information and sections are displayed. Breakpoints inside the datasource/delegate methods do not 'break' the program and no information is displayed.
Edit #2: From the storyboard, I segue to this TableViewController (WeaponSelectVC) using the following code after a button is pressed:
let window = UIWindow(frame:UIScreen.main.bounds)
window.makeKeyAndVisible()
window.rootViewController = UINavigationController(rootViewController: WeaponSelectVC())
I can see the table loaded for an instant before the Main.Storyboard ViewController (with the button) gets loaded on top of this.
The Table does not contain any of the information or sections when we see it for an instant (it also isn't loaded when I open this separately).
Below is the code from the WeaponSelect class:
struct section {
var name: String!
var items: [String]!
var collapsed: Bool
init(name: String, items: [String], collapsed: Bool = false) {
self.name = name
self.items = items
self.collapsed = collapsed
}
}
class WeaponSelectVC: UITableViewController {
var sections = [section]()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Weapons"
// Initialize the sections array
// Here we have three sections: Mac, iPad, iPhone
sections = [
section(name: "Canadian Weapons", items: ["Colt-browning machine gun M1895/14 (Canadian)","Lee Enfield (Canadian)", "Ross Rifle MK III(Canada)", "Webley revolver (Canadian)", "Lewis (Canadian)", "Mills bomb (Canadian)"]),
section(name: "German Weapons", items: ["KAR-98K (German)", "Mauser Gewehr 98 (German)", "Luger (German), Stick grenade (German)"]), ]
// self.tableView.reloadData()
self.tableView.dataSource = self
// self.tableView.delegate = self
// self.tableView.reloadData()
}
}
extension WeaponSelectVC {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sections.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].items.count
}
// Cell
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as UITableViewCell? ?? UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.textLabel?.text = sections[indexPath.section].items[indexPath.row]
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return sections[indexPath.section].collapsed ? 0 : 44.0
}
// Header
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "header") as? CollapsibleTableViewHeader ?? CollapsibleTableViewHeader(reuseIdentifier: "header")
header.titleLabel.text = sections[section].name
header.arrowLabel.text = ">"
header.setCollapsed(sections[section].collapsed)
header.section = section
header.delegate = self
return header
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44.0
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 1.0
}
}
//
// MARK: - Section Header Delegate
//
extension WeaponSelectVC: CollapsibleTableViewHeaderDelegate {
func toggleSection(_ header: CollapsibleTableViewHeader, section: Int) {
let collapsed = !sections[section].collapsed
// Toggle collapse
sections[section].collapsed = collapsed
header.setCollapsed(collapsed)
// Adjust the height of the rows inside the section
tableView.beginUpdates()
for i in 0 ..< sections[section].items.count {
tableView.reloadRows(at: [IndexPath(row: i, section: section)], with: .automatic)
}
tableView.endUpdates()
}
}
From which class is the WeaponSelectVC inherited? Your extension should be inheriting from UITableView .
Your extension class should look like
extension UITableView {

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
}

Xcode 7 - Cell content not displayed into an empty label

I'm trying to display a cell content into an empty UILabel, but after I upgraded to Xcode 7, the content didn't show up. I was following the same mechanism and it worked on Xcode 6, but since I'm new to Swift I may have something wrong in the code.
TableViewController:
import UIKit
class TableViewController: UITableViewController {
struct dataModel {
var name:String
var val:Double
}
let foods = [dataModel(name: "name1", val: 3.3),
dataModel(name: "name2", val: 5.5)]
#IBOutlet var table: UITableView!
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()
}
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 foods.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
// Configure the cell...
let foodCell = foods[indexPath.row]
cell.textLabel?.text = foodCell.name
return cell
}
var valueToPass:String!
var valueInt:Int!
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let indexPath = tableView.indexPathForSelectedRow;
let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;
valueToPass = currentCell.textLabel!.text
performSegueWithIdentifier("showCalc", sender: self)
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "showCalc") {
let viewController = segue.destinationViewController as! calcViewController
viewController.passedValue = valueToPass
}
}
}
ViewController where I want to display the tapped cell into an empty label:
import UIKit
class calcViewController: UIViewController {
#IBOutlet var text: UILabel!
#IBOutlet var empty1: UILabel!
var passedValue:String!
override func viewWillAppear(animated: Bool) {
empty1.text = passedValue
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
As a result, there is no error, but there is nothing displayed inside the empty label.
The other thing I want to achieve is to display the Int value into another label and then do some calculations, but this would be another question. Thanks in advance!
There are several issues in this code. First you are obviously missing some closing braces. But I assume this is a copy-paste error.
Why do you use didDeselectRowAtIndexPath? Don't you have a segue from the table view cell to the next controller? Then you should get the text label in prepareForSegue by using tableView.indexPathForSelectedRow.
If you like to keep it this way you should use didSelect... in stead of didDeselect....
You should take the value you want to pass to the next view controller direct from the data and not from the cell. You have the data you present in the table in the foods array.
Class names should always start with a capital letter. ALWAYS!
Having the data model within the controller is poor design. You should have the struct separated in its own file. In this case you could even hand the complete data object to the next view controller.

Resources