Swift: How to use "prepareForSegue" inside UICollectionViewCell? - ios

I have a UICollectionView inside a UITableView, I want to link another ViewController when the UICollectionViewCell is tapped by user. Inside the UITableViewCell, I downloaded all the data from the Internet and stored in an array. I created a Segue by control drag the CollectionViewCell to the new ViewController and chose "Push". Inside the new ViewController, I added an IBOutlet of UIImageView to show the image of the CollectionViewCell when user tapped the thumbnail. Now when I tapped the CollectionViewCell, it goes to the new ViewController, but there is no pics showed. here is my code, any suggestions?
In the UITableViewConroller:
import UIKit
class HomePageTableViewController: UITableViewController {
let sections: NSArray = ["latest news", "good news"]
var posts1: [Posts] = [Posts]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section < sections.count{
return sections[section] as? String
}
return nil
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sections.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 && indexPath.section == 0 {
let tableViewCell = tableView.dequeueReusableCellWithIdentifier("TableViewCell") as! TableViewCell
tableViewCell.getCategories()
// tableViewCell.scrollToNextCell()
// tableViewCell.startTimer()
return tableViewCell
}
and inside TableViewCell, here is the code:
import UIKit
import Alamofire
import AlamofireImage
class TableViewCell: UITableViewCell, UICollectionViewDataSource,
UICollectionViewDelegate {
var posts1: [Posts] = [Posts]()
var posts2: [Posts] = [Posts]()
var categories: [Category] = [Category]()
var selectedPost1: Posts?
#IBOutlet weak var theCollectionView: UICollectionView!
I download all the data from JSON and put them inside these arrays. inside this class, I also tried to call the function :
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
print("selected")
self.selectedPost1 = self.posts1
}
the print works when I tapped a cell, but I can't use "prepareForSegue" inside this function. I checked and found out that this function can only be used in ViewController, but how can I do that?
And inside the new ViewController, here is the code:
import UIKit
class DetailViewController: UIViewController {
#IBOutlet weak var postImageView: UIImageView!
var posts: [Posts] = [Posts]()
var selectedPost: Posts?
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
if let post = self.selectedPost{
let thumbnailUrlString = post.postThumbnailUrlString
let imageUrl: NSURL = NSURL(string: thumbnailUrlString)!
print(thumbnailUrlString)
postImageView.af_setImageWithURL(imageUrl)
}
}
}
Since when I download the data, I put them into 2 different array, posts1 and posts2. I want to show the corresponding images in the new ViewController. But I just created one "selectedPost" array, I am not sure is that the problem? and I am not sure if I reload the data to the "selectedPost" array, maybe thats why there is no images showing? really hope anyone can give me some suggestions. thanks

You should use prepareForSegue:. What you need to do is have a var selectedIndexPath which is set whenever you select a cell. Then in prepareForSegue: you can access the cell and it's properties i.e:
HomePageTableViewController: UITableViewController {
var selectedIndexPath: NSIndexPath?
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
selectedIndexPath = indexPath
}
public override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
super.prepareForSegue(segue, sender: sender)
let cell = theCollectionView.cellForItemAtIndexPath(selectedIndexPath)
//do what you need to do
}
}

Related

Segue from TableView into another Tableview using gesture

I have FirstTableView (TableView) which is populated by cells that have an image and label. If users tap the label, I want to segue into another tableview (SecondTableView), which will use the label from the previous tableview as a path(foldername) to search for images within that folder and display them as cells.
I have bits and pieces of the code written together, but I'm not quite sure where to pass the perform segue and prepare for segue functions.
Here is the extension of my FirstTableViewController, which populate the cells of the FirstTableView:
FirstTableView
extension FirstTableViewController: UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataCells.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let folderCell = dataCells[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "FirstTableCell") as! FirstTableViewCell
cell.setCell(cell:folderCell)
return cell
}
}
Here is the code for the FirstTAbleViewCell. Notice that I've created the UITapGestureRecognizer constant and a protocol. If the FolderLabel is clicked, I want to segue into the next tableview.
func setCell is just the function to populate the FirstTableViews.
FirstTableViewCells
import UIKit
protocol LabelCellDelegate {
func func1(sender:Any)
}
class FirstTableViewCell: UITableViewCell {
#IBOutlet weak var ImageView: UIImageView!
#IBOutlet weak var FolderLabel: UILabel!
var delegate: LabelCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
FolderLabel.isUserInteractionEnabled = true
let recognizer = UITapGestureRecognizer(target: self, action:Selector(("handleTap:")))
recognizer.numberOfTapsRequired = 1
self.FolderLabel.addGestureRecognizer(recognizer)
}
func handleTap(recognizer: UITapGestureRecognizer){
delegate!.func1(sender: self)
}
func setCell (cell : FolderCell){
self.ImageView.image = cell.image
self.FolderLabel.text = cell.label
}
}
Next is the SecondTableViewController.
Somehow, after the tap of the cell from the FirstTableView I want to get the label name that was tapped, and use that name as a directory to search.
Grab all the images within the directory and display them as images in cells in SecondTableView. I'm not quite sure where I should be calling the gesture function and which TableViewController should be the delegate of the cell protocol.
SecondTableView
import UIKit
class SecondTableViewController: UIViewController {
var Imagefiles: [String] //Imagefiles String. This are all images from tapped folder label.
var CellObjects: [folderCell] // Cellobjects to fill the cells. contains images and image names.
// need to get folder name from FirstTableViewCell how?
override func viewDidLoad() {
super.viewDidLoad()
imageFiles = getImageObjects(folder: Foldercell) //how to get access to folderCell???????
cellObjects = createArray(imageFiles: imageFiles)
}
func getImageObjects(folder: FolderCell) -> imageFiles: String {
//FUNCTION To search tapped label and grab all image file paths.
func createArray(imageFiles: string)-> tempArray: [folderCell]{
//We use this function to take the image files from above function and
//create cell objects to populate our cells
//in SecondTableView
}
}
}
}
extension ViewController: LabelCellDelegate{
func1(folderLabel : String) {
return folderLabel
}
}
extension LablesTableView:UITableViewDataSource,UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return CellObjects.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellFolderObject = folderObjects[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "SecondCell") as! LabelCell
let folderCell = CellObjects[indexPath.row]
cell.setCell(cell: folderCell)
return cell
As you can see, I haven't called perform segue and prepare for segue. I'm not sure where I should be calling them.
I'm also unsure about where the delegate to the gesture protocol should be.
Thank you.
Inside cellForRowAt set
cell.delegate = self
//
then inside this delegate function of the VC ( conform to the protocol LabelCellDelegate )
extension FirstTableViewController:LabelCellDelegate {
func func1(sender: FirstTableViewCell) {
self.performSegue(withIdentifier: "goToSecond", sender:sender.FolderLabel.text!)
}
}
//
the VC method is triggered from here
func handleTap(recognizer: UITapGestureRecognizer){
delegate!.func1(sender: self)
}
//
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let secondController = segue.destination as? SecondTableViewController {
secondController.sendedStr = sender as! String
}
}

I was wondering how to make a cell go to another view controller in Xcode 9, swift

I've been trying to figure out how to configure a cell to go to another view, in this case, I'm listing a group of services after login and when the user taps on a service they like, it takes them to a map. But I don't know how to set the cell up in a way that it takes them to the map when its tapped. I've tried creating a segue but nothing happens when the cell is tapped. I'm new to programming and was wondering if someone could explain this.
I've watched a bunch of youtube videos which gave me the understanding on how to set up the cell (basic stuff).
Would really appreciate some advice, thanks!
Hope this post helps anyone that's dipping their feet into the programming journey!
Thank you, happy coding!
Here is the code I currently have:
import UIKit
struct cellData {
let cell : Int!
let text : String!
let image : UIImage! }
class ListServicesTVC: UITableViewController {
var arrayOfCellData = [cellData]()
override func viewDidLoad() {
arrayOfCellData = [cellData(cell : 1, text : "Barber Services", image : #imageLiteral(resourceName: "barberservice") ),
cellData(cell : 2, text : "Salon Services", image : #imageLiteral(resourceName: "salonservice"))]
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayOfCellData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if arrayOfCellData[indexPath.row].cell == 1 {
let cell = Bundle.main.loadNibNamed("BarberServiceCell", owner: self, options: nil)?.first as! BarberServiceCell
cell.barberImageView.image = arrayOfCellData[indexPath.row].image
cell.barberServicesLabel.text = arrayOfCellData[indexPath.row].text
return cell
}
else if arrayOfCellData[indexPath.row].cell == 2 {
let cell = Bundle.main.loadNibNamed("SalonServicesCell", owner: self, options: nil)?.first as! SalonServicesCell
cell.salonImageView.image = arrayOfCellData[indexPath.row].image
cell.salonServicesLabel.text = arrayOfCellData[indexPath.row].text
return cell
}
else {
let cell = Bundle.main.loadNibNamed("BarberServiceCell", owner: self, options: nil)?.first as! BarberServiceCell
cell.barberImageView.image = arrayOfCellData[indexPath.row].image
cell.barberServicesLabel.text = arrayOfCellData[indexPath.row].text
return cell
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if arrayOfCellData[indexPath.row].cell == 1 {
return 120
}
else if arrayOfCellData[indexPath.row].cell == 2 {
return 120
}
else {
return 120
}
}
}
Just follow the steps below:
create A tableView Outlet in ViewController Class.
create a TableViewCell Class and register with tableView Outlet.
then, create a DetailViewController Class ( i.e, When You click on a particular cell, it should show details of that particular cell)
In main "ViewController" do the following code
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {'
#IBOutlet var tableView: UITableView!
var tableData: [String] = ["Apple", "Samsung", "LG"]
// 1
override func viewDidLoad() {
super.viewDidLoad()
// Register customCell with tableView Outlet
let nib = UINib(nibName: "CustomTableViewCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "cell")
}
// 2
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.tableData.count
}
// 3
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: CustomTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! CustomTableViewCell
// injecting data to cell
cell.lblCompanyName.text = tableData[indexPath.row]
cell.imgCompanyName.image = UIImage(named: tableData[indexPath.row])
return cell
}
// 4
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let detailObj=DetailViewController(nibName: "DetailViewController", bundle: nil)
self.navigationController?.pushViewController(detailObj, animated: true)
detailObj.nameVar=tableData[indexPath.row]
detailObj.imgStr=tableData[indexPath.row]
}
In "CustomTableViewCell" class
class CustomTableViewCell: UITableViewCell {
#IBOutlet var imgCompanyName: UIImageView!
#IBOutlet var lblCompanyName: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}}
in "DetailViewController"
class DetailViewController: UIViewController {
#IBOutlet var name: UILabel!
#IBOutlet var image: UIImageView!
var nameVar:String?
var imgStr:String?
override func viewDidLoad() {
name.text=nameVar
image.image=UIImage(named: imgStr!)
super.viewDidLoad()
// Do any additional setup after loading the view.
}}
End of the Code
I think I am clear, if you have any quires just comment below.
Hi try the following set of code, I have added few additional changes in your code which is necessary for passing the details, I hope it will solve your issue.
I have added only the extra codes which you needed
class ListServicesTVC: UITableViewController {
// Add this variable in this class and use it whereever you needed it in this class
var selectedItem: cellData?
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Now maintain the selected data in the local variable we declared
selectedItem = arrayOfCellData[indexPath.row]
// Now perform the segue operation
performSegue(withIdentifier: "VIEW_CONTROLLER_IDENTIFIER_OF_MAP_CLASS", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "VIEW_CONTROLLER_IDENTIFIER_OF_MAP_CLASS" {
let destinationVC = segue.destination as? VIEW_CONTROLLER_IDENTIFIER_OF_MAP_CLASS
destinationVC?.selectedItem = self.selectedItem // Pass the selected item here which we have saved on didSelectRotAt indexPath delegate
}
}
In Second class:
class VIEW_CONTROLLER_IDENTIFIER_OF_MAP_CLASS: UIViewController {
// Add this variable in this class and use it whereever you needed it in this class
var selectedItem: cellData?

How do I send specific data based on which cell is clicked?

I have a tableview with a bunch of concerts, and when x cell is clicked, I want the artist of that concert to populate the new tableView. Below is the code for the first view controller (the view controller with all the concerts).
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView1: UITableView!
var arrayOfConcerts: [concert] = [concert]()
override func viewDidLoad()
{
super.viewDidLoad()
self.setUpConcerts()
self.tableView1.rowHeight = 145.0
}
func setUpConcerts()
{
var ACL = concert(imageName: "ACL2015.png")
let Landmark = concert(imageName: "Landmark.png")
let BostonCalling = concert(imageName: "BostonCalling.png")
let Lolla = concert(imageName: "Lolla.png")
arrayOfConcerts.append(ACL)
arrayOfConcerts.append(Landmark)
arrayOfConcerts.append(BostonCalling)
arrayOfConcerts.append(Lolla)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayOfConcerts.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = self.tableView1.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomCell
let concerts = arrayOfConcerts[indexPath.row]
cell.setCell(concerts.imageName)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("concertartist", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
}
}
Below is the code for the Artist View Controller (the second
viewcontroller). This tableView should be populated with specific
artists.
How would I go about doing that?
class ArtistConcerts: UIViewController, UITableViewDataSource, UITableViewDelegate {
var arrayOfArtists: [artist] = [artist]()
#IBOutlet weak var tableViewArtists: UITableView!
override func viewDidLoad()
{
super.viewDidLoad()
self.setUpArtists()
}
func setUpArtists()
{
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayOfArtists.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableViewArtists.dequeueReusableCellWithIdentifier("", forIndexPath: indexPath) as! CustomCell
let artists = arrayOfArtists[indexPath.row]
cell.setCell(artists.imageNameArtist)
return cell
}
}
You need to do this in the prepareForSegue method.
let vc = segue!.destinationViewController as! ArtistConcerts
if let rowSelected = tableView.indexPathForSelectedRow()?.row {
vc.arrayOfArtists = artistsPerforming[0]//this is an array
}
then, set whatever data you need to actually populate the tableView in that new view controller. I am not 100% sure on what you are trying to do though. Does my answer make sense?
you can send data once the cell is pressed to another viewcontroller by using didSelectRowAtIndexPath or prepareForSegue or didSelectRowAtIndexPath + prepareForSegue
let's say you are using prepareForSegue, things you will need
the segue identifier name
cast the destinationController to the controller you want to send the data
the indexPath.row where the cell was selected
then set the variable or variables or data structure that should receive data
Create a segue when you pressed CTRL + Drag from your cell into another viewcontroller
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "Name_Of_Segue"
{
let destination = segue.destinationViewController as! NAME_Of_ViewController
let indexPath = mytableview.indexPathForSelectedRow!
let data = arrayOfArtists[indexPath.row]
destination.artist = data
}
mytableview is an IBOutlet from your tableview
artist is a variable that is declared in your destination controller
destination.artist = data this line of code is passing data from the specific cell then send it to your destination cell

How to know which cell in tableview has been selected

I have got a view controller which contains a tableview, this tableview contains dynamic cells done in storyboard. Most cells contain a textfield and in the view controller i need to detect when the textfields have been selected and which cell it was. (I load a popover pointing to the cell, and this must be called from the view controller).
Cell code
import UIKit
class AddNew_Date_Cell: UITableViewCell {
#IBOutlet var Label: UILabel!
#IBOutlet var textField: UITextField!
func loadItem(var data:NSArray) {
Label.text = data[0] as? String
}
}
ViewControllerCode
import UIKit
class AddNewDetailView: UIViewController, UITableViewDelegate, UITableViewDataSource, UIPopoverPresentationControllerDelegate, UITextFieldDelegate {
#IBOutlet var tableView: UITableView!
var items : NSMutableArray!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch(items[indexPath.row][1] as! Int)
{
...
case 2:
var cell:AddNew_Date_Cell = tableView.dequeueReusableCellWithIdentifier("AN_Date_Cell") as! AddNew_Date_Cell
cell.loadItem(items[indexPath.row] as! NSArray, view: self)
cell.textField.delegate = self
return cell
...
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
//Need to know here which cell the textfield is attached to
turn true
}
}
Each time i select a textfield view I'm hitting a breakpoint in "textFieldShouldBeginEditing" however i have no idea which cell its in.
if i select the textfield in a cell "didSelectRowAtIndexPath" is never hit.
How do i find out which cell has been selected.
Thanks
You need to set the interactions from user off while the text field is not been edit, in cellForRowAtIndexPath add this line
cell.textField.userInteractionEnabled = false
In the didSelectRowAtIndexPath you will need to enable again for edition otherwise the user won't be to touche it if they want to and call first responder:
cell.textField.userInteractionEnabled = true
cell.textField.becomeFirstResponder()
once the user finish editing in textFieldShouldEndEditing you disable the interaction again:
cell.textField.userInteractionEnabled = false
This way the cellForRowAtIndexPath will always be called but will be up to you to set the user to use the correct UITextField.
I hope that helps you
You could use a custom cell class with a delegate protocol letting you know when a text field has started editing.
The custom cell would be the delegate of the text field and the view controller would be the delegate of the custom cell.
For a basic example, your cell class could look like the following:
import UIKit
protocol TextFieldCellDelegate {
func textFieldCellDidBeginEditing(cell: TextFieldCell)
}
class TextFieldCell: UITableViewCell {
#IBOutlet weak var textField: UITextField!
var delegate: TextFieldCellDelegate?
}
extension TextFieldCell: UITextFieldDelegate {
func textFieldDidBeginEditing(textField: UITextField) {
delegate?.textFieldCellDidBeginEditing(self)
}
}
And your view controller would implement the method like this:
extension ViewController: TextFieldCellDelegate {
func textFieldCellDidBeginEditing(cell: TextFieldCell) {
println(cell)
// Do something with cell
}
}
If you want to find out the index of your cell write the below code in func textFieldShouldBeginEditing(textField: UITextField)
var index = 0
var position: CGPoint = textField.convertPoint(CGPointZero, toView: self.<your_table_outlet_name>)
if let indexPath = self.<your_table_outlet_name>.indexPathForRowAtPoint(position)
{
index = indexPath.row
}

UITextField and UITableView on a single view controller

I'm trying to make a view controller that has one text field that populates the tableview below, ideally the user will be able to continue to add to the tableview without jumping between two views.
I previously had it working with the text field on one view that populates a UITableView and used prepareForSegue to push the data to the table, but I haven't been able to get it to work with just one view.
Can anyone please point out where I'm going wrong or push me to a tutorial / documentation to help?
Edit: Clarity
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
#IBOutlet var tableView: UITableView!
#IBOutlet weak var textField: UITextField!
var items: [String] = ["Pls", "work", "pls", "work", "pls"]
var foodGroup: FoodGroup = FoodGroup(itemName:"")
//var foodGroup: [FoodGroup] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel.text = self.items[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("Selected cell #\(indexPath)")
}
func addFood(sender: AnyObject!) {
if (countElements(self.textField.text) > 0) {
self.foodGroup = FoodGroup(itemName: self.textField.text)
}
}
#IBAction func addFoodToList() {
let source = FoodGroup
let foodGroup:FoodGroup = source.foodGroup
if foodGroup.itemName != "" {
self.foodGroup.append(foodGroup)
self.tableView.reloadData()
}
}
}
It seems like your intention here is to have your dataSource be an array of FoodGroup objects. If this is indeed the case you can get rid of your foodGroup instance variable and update your items definition to be like so:
var items = [FoodGroup]()
then in addFoodToList:
if self.textField.text != "" {
let foodGroup = FoodGroup(itemName: self.textField.text)
self.items.append(foodGroup)
self.tableView.reloadData()
}
and finally in cellForRowAtIndexPath:
var cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
let foodGroup = self.items[indexPath.row] as FoodGroup
cell.textLabel.text = foodGroup.itemName
return cell
Also I don't quite see the intention of your the addFood(sender: AnyObject!) function. Looks like cruft. I would get rid of it. Good luck!

Resources