Passing Data Tableview -> Viewcontroller - ios

I have this tableview and I would like to pass the username to a view controller and display it there in a label, but it does not work. The username comes from a firebase database. I also checked other questions but cannot adopt it to my problem. I am not expert in coding:
import Foundation
import UIKit
import Firebase
import FirebaseDatabase
import FirebaseAuth
struct user {
let username : String!
}
class MainScreen: UITableViewController {
var Users = [user]()
override func viewDidLoad() {
let databaseRef = FIRDatabase.database().reference()
databaseRef.child("users").queryOrderedByKey()
.observe(.childAdded, with: { snapshot in
print(snapshot)
let username = (snapshot.value as? NSDictionary)!["username"] as! String
print(username)
self.Users.append(user(username: username))
self.tableView.reloadData()
print(self.Users)
})
}
override func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return Users.count
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
let nameLbl = cell?.viewWithTag(1) as! UILabel
nameLbl.text = self.Users[indexPath.row].username
return cell!
}
#IBAction func ShowDetail(_ sender: Any) {
var selectedLabel:String?
func tableView(tableView: UITableView,
didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("Row \(indexPath.row)selected")
selectedLabel = self.Users[indexPath.row].username
performSegue(withIdentifier: "detailView", sender: self)
}
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "detailView") {
let vc = segue.destination as! CallDetail
vc.stringPassed = selectedLabel!
}
}
}
And the receiving ViewController looks like this:
import UIKit
class CallDetail: UIViewController {
#IBOutlet weak var UserName: UILabel!
var stringPassed = String()
override func viewDidLoad() {
super.viewDidLoad()
UserName = stringPassed.text
}
}

Both of didSelectRowAtIndexPath and prepareForSegue methods should be outside of #IBAction func ShowDetail(_ sender: Any) (actually, I can't figure the purpose of it):
declare selectedLabel as an instance variable and separate the methods:
import Foundation
import UIKit
import Firebase
import FirebaseDatabase
import FirebaseAuth
struct user {
let username : String!
}
class MainScreen: UITableViewController {
// 'selectedLabel' should be here:
var selectedLabel:String?
var Users = [user]()
override func viewDidLoad() {
let databaseRef = FIRDatabase.database().reference()
databaseRef.child("users").queryOrderedByKey().observe(.childAdded, with: {
snapshot in
print(snapshot)
let username = (snapshot.value as? NSDictionary)!["username"] as! String
print(username)
self.Users.append(user(username: username))
self.tableView.reloadData()
print(self.Users)
})
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Users.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
let nameLbl = cell?.viewWithTag(1) as! UILabel
nameLbl.text = self.Users[indexPath.row].username
return cell!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("Row \(indexPath.row)selected")
selectedLabel = self.Users[indexPath.row].username
performSegue(withIdentifier: "detailView", sender: self)
}
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "detailView") {
let vc = segue.destination as! CallDetail
vc.stringPassed = selectedLabel!
}
}
// just remove it if you don't need it...
#IBAction func ShowDetail(_ sender: Any) {
}
}
Also, make sure that the tableView data source and delegate are connected to the viewController.

First you need to remove
tableView(tableView: UITableView, didSelectRowAtIndexPath because it will be called automatically when you click on a cell, if you've set the tableView delegate to the viewController.
prepareForSegue will be called after performSegue(withIdentifier: "detailView", sender: self) and delete ShowDetail(_ sender: Any) it's not necessary.
and change these lines
let nameLbl = cell?.viewWithTag(1) as! UILabel
nameLbl.text = self.Users[indexPath.row].username
to
cell.textLabel?.text = self.Users[indexPath.row].username

Related

How to make data transition between table view cells with where button out of table view?

I have two custom table views. I need to pass first and second cell datas of DestinationTableView to first cell of MyCartTableView. How can I make transition between this two table view cells with outside of tableView.
I did tableView.indexPathForSelectedRow but this time I need to make with UIButtonoutside of tableView.
Below triggered with tableView cell.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "cellForFoodSegue" {
if let destinationViewController = segue.destination as? DetailViewController
{
let indexPath = self.mainTableView.indexPathForSelectedRow!
var foodNameArray: String
var foodPriceArray: Double
foodNameArray = foodNames[indexPath.row]
foodPriceArray = foodPrices[indexPath.row].purchaseAmount
destinationViewController.detailFoodName = foodNameArray
destinationViewController.detailFoodPrice = foodPriceArray
}
}
}
I tried below code but I did not success passing data with button.
#IBAction func addBasket(_ sender: Any) {
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "addToCartSegue") {
if let addToCartVC = segue.destination as? MyCartViewController {
let selectedCell = sender as! UITableViewCell
let indexPath = self.detailTableView.indexPath(for: selectedCell)
var foodNameArray: String
var foodPriceArray: Double
foodNameArray = foodNames[indexPath.row]
foodPriceArray = prices[indexPath.row].purchaseAmount
addToCartVC.fromDetailFoodName = foodNameArray
addToCartVC.fromDetailFoodPrice = prices[(indexPath?.row)!].purchaseAmount
}
}
}
Belows my MyViewController codes. Which is my added objects when tapped to addBasket button
class MyCartViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var fromDetailFoodName: [String?] = []
var fromDetailFoodPrice = Double()
var nameLabel = MyCartTableViewCell()
#IBOutlet weak var myCartTableView: UITableView!
#IBOutlet weak var totalPriceLabel: UILabel!
let foodNames = [
"Hamburger big mac",
"Cemal",
"Emre",
"Memo"
]
//TODO-: Delete my cart
#IBAction func deleteMyCart(_ sender: Any) {
}
//TODO: - Approve my cart
#IBAction func approveCart(_ sender: Any) {
}
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section == 0 ? 1 : foodNames.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCartCell", for: indexPath) as! MyCartTableViewCell
cell.myCartFoodNameLabel?.text = fromDetailFoodName.description
cell.myCartFoodPriceLabel?.text = "\(fromDetailFoodPrice)₺"
return cell
}
}
You should get the index path of the data you want to pass in func addBasket(_ sender: Any).
For example, you can save index path as a property that referenced in class.
class StartViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var selectedIndexPath: IndexPath?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedIndexPath = indexPath
}
#IBAction func addBasket(_ sender: Any) {
if let indexPath = selectedIndexPath {
let destinationVC = MyCartViewController()
destinationVC.detailFoodName = foodNames[indexPath.row]
destinationVC.detailFoodPrice = foodPrices[indexPath.row].purchaseAmount
}
}
}
In MyCartViewController which is destination VC.
class MyCartViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var fromDetailFoodNames: [String?] = []
var fromDetailFoodPrices: [Double?] = []
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 1 && indexPath.last! <= fromDetailFoodPrices.indices.last! {
let cell = myCartTableView.dequeueReusableCell(withIdentifier: "myCartCell", for: indexPath) as! MyCartTableViewCell
let name = fromDetailFoodNames[indexPath.row]?.description ?? ""
let price = fromDetailFoodPrices[indexPath.row]
cell.myCartFoodNameLabel?.text = name
cell.myCartFoodPriceLabel?.text = "\(price)₺"
return cell
}
}
}
BTW, for better coding, you can implement OOP concept in your code. detailFoodName and detailFoodPrice should be in ONE object. Besides, var foodNameArray: String naming could be confusing. Rename it as var foodName: String would be better.

Pass Data (Label) from TableViewCell to another ViewController

I want to pass the Label from a TableViewCell to a ViewController when I click on the Cell. In the end it should be like twitter, that if you click on a cell with a Label you get passed on a detailViewController with the same Label init.
My Code doesn't work as I just get the blanket Label from the Storyboard...
import UIKit
import Firebase
class JobTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var valueToPass:String!
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
// Arvice return to count jobs
return jobs.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You selected cell #\(indexPath.row)!")
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell
let valueToPass = currentCell.textLabel?.text
print("value: \(valueToPass)")
performSegue(withIdentifier: "toDetails", sender: valueToPass)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "JobCell", for: indexPath) as! JobTableViewCell
let job = jobs[indexPath.row]
cell.job = job
//spacing
cell.contentView.backgroundColor = UIColor.clear
let whiteRoundedView : UIView = UIView(frame: CGRect(x: 10, y: 8, width: self.view.frame.size.width - 20, height: 120))
whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [0.36, 0.39, 0.40, 1.0])
whiteRoundedView.layer.masksToBounds = false
whiteRoundedView.layer.cornerRadius = 2.0
whiteRoundedView.layer.shadowOffset = CGSize(width: 0, height: 0)
whiteRoundedView.layer.shadowOpacity = 0.0
cell.contentView.addSubview(whiteRoundedView)
cell.contentView.sendSubview(toBack: whiteRoundedView)
cell.emojiLabel.text = cell.emojiString
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toDetails" {
let destinationViewController = segue.destination as! JobDetailViewController
destinationViewController.valueToPass = (sender as? String)!
}
}
My Cell:
import UIKit
import Firebase
class JobTableViewCell: UITableViewCell {
#IBOutlet weak var jobLabel: UILabel!
var job: Job! {
didSet {
jobLabel.text = job.text
}
}
}
Job.Swift:
import Foundation
import Firebase
class Job{
var text: String = ""
let ref: DatabaseReference!
init(text: String) {
self.text = text
ref = Database.database().reference().child("jobs").childByAutoId()
}
init(snapshot: DataSnapshot)
{
ref = snapshot.ref
if let value = snapshot.value as? [String : Any] {
text = value["text"] as! String
}
}
func save() {
ref.setValue(toDictionary())
}
func toDictionary() -> [String : Any]
{
return [
"text" : text,
]
}
}
And in my DestinationController:
import UIKit
import Firebase
class JobDetailViewController: UIViewController {
#IBOutlet weak var jobDetail: RoundText!
var valueToPass: String = ""
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
jobDetail.text = valueToPass
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Jobinformation"
}
}
You should not be using cells to store data. You should have a data model that represents the data you are showing in the cells, and you should use the indexPath of the selected cell to look up the data in your data model.
Quick solution:
Change
performSegue(withIdentifier: "yourSegueIdentifer", sender: self) to performSegue(withIdentifier: "yourSegueIdentifer", sender: valueToPass)
2.Your prepare for Segue method should looks like this:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "yourSegueIdentifer" {
let destinationViewController = segue.destination as! AnotherViewController
destinationViewController.valueToPass = sender as? String
}
}
On AnotherViewController create var valuteToPass: String = "" and set your label.text = valueToPass
But I think you should not use currentCell.textLabel.text value, instead use the original value. (like if you set your currentCell as cell.textLabel.cell = array[indexPath.row], your valueToPass should be valueToPass = array[indexPath.row])
EDIT:
You use didDeselectRowAt method, instead of didSelectRowAt.
Change func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) to
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
Don't use global variable, create it in didSelectRowAt.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You selected cell #\(indexPath.row)!")
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell
let valueToPass = currentCell.textLabel?.text
print("value: \(valuteToPass)")
performSegue(withIdentifier: "toDetails", sender: valueToPass)
}
On DestinationController:
class DestinationController: UIViewController {
var valuteToPass: String = ""
override func viewDidLoad() {
super.viewDidLoad()
jobLabel.text = valueToPass
}
}
EDIT2
JobTableViewController
delete var valueToPass:String!
Change let valueToPass = jobs[indexPath.row].text instead of let valueToPass = currentCell.textLabel?.text
I checked this change in your code, this will work.
Hi I cant comment but im using #Dris answer and I kept getting this error that says
Could not cast value of type 'UITableViewCell' (0x115464e18) to 'NSString' (0x10fa594c8).
The SIGABRT targets the line destinationViewController.valueToPass = (sender as? String)!
Why is that?
this is basically my code
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Determine what to do when a cell in a particular section is selected.
print("did select: \(indexPath.row) ")
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell
valueToPass = currentCell.textLabel?.text
print("valueToPass: \(String(describing: valueToPass))")
performSegue(withIdentifier: "cellToView", sender: self)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell?
if tableView == self.tableView {
let currentNotif = notificationList[indexPath.row]
cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
cell?.textLabel?.text = currentNotif.notifType
cell?.detailTextLabel?.text = "\(currentNotif.notifTime) \n\(currentNotif.notifContent)"
}
if tableView == self.tableViewAnnounce {
let currentAnnounce = announcementList[indexPath.row]
cell = tableView.dequeueReusableCell(withIdentifier: "cellAnn", for: indexPath) as UITableViewCell
cell?.textLabel?.text = currentAnnounce.annouceType
cell?.detailTextLabel?.text = "\(currentAnnounce.annouceTime) \n\(currentAnnounce.annouceContent)"
}
return cell!
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "cellToView" {
// perform custom segue operation.
let destinationViewController = segue.destination as! ExtendedAnnouncementViewController
destinationViewController.valueToPass = (sender as? String)!
}
}
I'd avoid using a global variable to pass the data to the destination view controller. Defer the lookup until you are ready to pass the data.
And, avoid using force unwrap, it leads to runtime crashes.
Use something like this instead:
let segueIdentifier = "yourSegueIdentifer"
let labelDataSource: [String] = ["SomeText"]
func label(forIndexPath indexPath: IndexPath) -> String? {
let index = indexPath.row
guard labelDataSource.indices.contains(index) else { return nil }
return labelDataSource[index]
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: segueIdentifier, sender: indexPath)
}
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard segue.identifier == segueIdentifier,
let indexPath = sender as? IndexPath,
let destinationViewController = segue.destination as? AnotherViewController else { return }
destinationViewController.valuePassed = label(forIndexPath: indexPath)
}

How extract from UITableView data (UIImage and String) to another ViewController

I want to pass the storage data contained in a TableView and pass it to another ViewController. My customCell has an UIImage and a String.
When the user press the cell I want to show a "detail view controller" with the UIImage and a label containing the info of the cell selected.
Here is my code:
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var dataTableView: UITableView!
var myList = [dataList]()
var textToBeSent: String = ""
var selectedImage: UIImage?
var selectedLabel: String?
//Load Items To List
func loaditems(){
let item1 = dataList(photoList: UIImage.self(), itemDescription: "Descripcion Aqui")
let item2 = dataList(photoList: UIImage.self(), itemDescription: "Aqui tmb")
myList += [item1,item2]
}
//var list = ["Documento 1", "Documento 2", "Documento 3"]
override func viewDidLoad() {
super.viewDidLoad()
if let savedData = loadSavedItems(){
myList += savedData
} else {
loaditems()
}
//dataTableView.register(UITableViewCell.self, forCellReuseIdentifier: "reusablecell")
// Do any additional setup after loading the view, typically from a nib.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return myList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "prototype", for: indexPath) as! PrototypeCell
let itemsinCell = myList[indexPath.row]
cell.imageItem.image = itemsinCell.photoList
cell.itemDescription.text = String(itemsinCell.itemDescription)
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete{
myList.remove(at: indexPath.row)
dataTableView.reloadData()
}
saveToSavedData()
}
Here is the func where I want to pass the data of a certain cell.
The data is from a Swift file stored in a "DataList" using aDecoder NSCoder.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Row \(indexPath.row) selected")
selectedImage! = myList[indexPath.row].photoList
selectedLabel! = myList[indexPath.row].itemdescription
performSegue(withIdentifier: "selectedRowSegue", sender: myList[indexPath.row])
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "selectedRowSegue"){
let chosenRowViewController = segue.destination as! chosenRowViewController
chosenRowViewController.image3 = selectedImage?.photoList
chosenRowViewController.label3 = selectedLabel?.itemDescription
}
}
Unwind a segue in order to fill up the cells with data from previous
ViewController:
//Unwinde Segue
#IBAction func unWindlToList(sender: UIStoryboardSegue){
if let sourceViewController = sender.source as? ProcessViewController, let item = sourceViewController.item{
let newIndexPath = IndexPath(row: myList.count, section: 0)
myList.append(item)
dataTableView.insertRows(at: [newIndexPath], with: .automatic)
}
saveToSavedData()
}
//Archive Data
func saveToSavedData(){
NSKeyedArchiver.archiveRootObject(myList, toFile: (dataList.fileFolder?.path)!)
}
//Unarchive Data
func loadSavedItems() -> [dataList]?{
return NSKeyedUnarchiver.unarchiveObject(withFile: (dataList.fileFolder?.path)!) as? [dataList]
}
}
class PrototypeCell: UITableViewCell {
#IBOutlet weak var itemDescription: UILabel!
#IBOutlet weak var imageItem: UIImageView!
}
just replace prepare(for segue: UIStoryboardSegue, sender: Any?) function with below code
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "selectedRowSegue"), let list = sender as? dataList {
let chosenRowViewController = segue.destination as! chosenRowViewController
chosenRowViewController.image3 = list.photoList
chosenRowViewController.label3 = list.itemDescription
}
}
There are several things that stand out.
1- var myList = [dataList]() dataList is a Class, classes should be capitalized. It should be var myList = [DataList]()
2- You have this as a class property but it's not used anywhere in the code you posted so why did you add it and what is it's purpose? var textToBeSent: String = ""
3- You have these 2 class property variables
var selectedImage: UIImage?
var selectedLabel: String?
to hold the data from [myList] but you really don't need them because you can just access the data from [myList] using dot notation inside prepareForSegue (read the commented out code in prepareForSegue).
4- In prepareForSegue you have let chosenRowViewController = segue.destination as! chosenRowViewController. ChosenRowViewController is a class and it should be capitalized like so:
let chosenRowViewController = segue.destination as! ChosenRowViewController // it's capitalized after the as!
Here's the code a little cleaned up.
#IBOutlet weak var dataTableView: UITableView!
var myList = [DataList]()
func loaditems(){
let item1 = dataList(photoList: UIImage.self(), itemDescription: "Descripcion Aqui")
let item2 = dataList(photoList: UIImage.self(), itemDescription: "Aqui tmb")
myList.append(item1)
myList.append(item2)
}
override func viewDidLoad() {
super.viewDidLoad()
// everything you already have inside here...
}
// your tableView datasource methods...
5- Since your using prepareForSegue you don’t need didSelectRowAt indexPath
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "selectedRowSegue"){
// get the indexPath for the selectedRow
let indexPath = tableView.indexPathForSelectedRow
let chosenRowViewController = segue.destination as! ChosenRowViewController
chosenRowViewController.image3 = myList[indexPath!.row].photoList // use dot notation to access the photoList property
chosenRowViewController.label3 = myList[indexPath!.row].itemDescription // use dot notation to access the itemDescription property
}
}
You have made a mistake in your didSelectRowAt, while calling performSegue you have to pass the controller which is the sender, in your case it is your current UIVIewController, so you have to write self as sender controller. So your corrected methog will look like below code snippet:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Row \(indexPath.row) selected")
selectedImage! = myList[indexPath.row].photoList
selectedLabel! = myList[indexPath.row]
performSegue(withIdentifier: "selectedRowSegue", sender: self)
}

Error while passing data between two ViewControllers

I get the following error after passing data from one ViewController to another.
no data
eventStruct(title: What are we gonna do today?, date: 2017-07-13, location: House3, description: Hello beautiful people!)
2017-06-15 22:01:05.697 RUC-App 1.0[48760:5792168] Warning: Attempt to present <RUC_App_1_0.EventViewController: 0x7fb686636460> on <RUC_App_1_0.NewsfeedViewController: 0x7fb68662e6a0> whose view is not in the window hierarchy!
The code from the first ViewController:
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
class NewsfeedViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var ref:DatabaseReference!,
posts = [eventStruct]()
#IBOutlet weak var tableview: UITableView!
var propertStruct : (Any)? = nil
override func viewDidLoad() {
super.viewDidLoad()
loadNews()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func loadNews() {
ref = Database.database().reference()
ref.child("events").queryOrderedByKey().observe(.childAdded, with: { (snapshot) in
if let valueDictionary = snapshot.value as? [AnyHashable:String]
{
let title = valueDictionary["Title"]
let location = valueDictionary["Location"]
let date = valueDictionary["Date"]
let description = valueDictionary["Description"]
self.posts.insert(eventStruct(title: title, date: date, location: location, description: description), at: 0)
self.tableview.reloadData()
}
})
}
///////////////////////// Table View Content \\\\\\\\\\\\\\\\\\\\\\\\\\
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let label1 = cell.viewWithTag(1) as! UILabel
label1.text = posts[indexPath.row].title
let label2 = cell.viewWithTag(2) as! UILabel
label2.text = posts[indexPath.row].location
let label3 = cell.viewWithTag(3) as! UILabel
label3.text = posts[indexPath.row].date
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "showDetails"){
let secondViewController = segue.destination as? EventViewController
secondViewController?.data = sender as? eventStruct
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "showDetails", sender: posts[indexPath.row])
}
/////////////////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
}
struct eventStruct {
let title: String!
let date: String!
let location: String!
let description: String!
}
The code of the second ViewController:
import UIKit
class EventViewController: UIViewController {
var data: eventStruct?
#IBOutlet weak var titleLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
print (data ?? "no data")
self.titleLabel.text = self.data?.title
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You should not have both triggered and manual segues happening at the same time.
Try this:
Delete your didSelectRowAt function (or comment it out), and replace prepare() with:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "showDetails"){
let secondViewController = segue.destination as? EventViewController
if let idx = tableView.indexPathForSelectedRow {
secondViewController?.data = posts[idx.row]
}
}
}

Passing coredata from tableview to another tableview

I am struggling with getting my care data to populate my second tableview controller. The data is populating the first tableview and I can select a row and the segue is used to go to the second table but the labels are not populated.
I've looked all over and have found older samples or obj-c but I cannot figure it out, so any help pointing this n00b in the right direction will be helpful.
Here is what I have, I think I am missing how to populate a variable to pass in prepareForSegue in the list tableview, but I could be wrong. I get a warning error in that function (Warning cannot assign value of type 'ListEntity' to type '[ListEntity]').
CoreData
Entity = ListEntity
Attributes = title, event & location (all as Strings)
listTableViewController
import UIKit
import CoreData
class ListTableViewController: UITableViewController {
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var lists = [ListEntity]()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "The List"
let addButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: #selector(ListTableViewController.addButtonMethod))
navigationItem.rightBarButtonItem = addButton
}
func addButtonMethod() {
print("Perform action")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
reloadData()
tableView.reloadData()
}
func reloadData() {
let fetchRequest = NSFetchRequest(entityName: "ListEntity")
do {
if let results = try managedObjectContext.executeFetchRequest(fetchRequest) as? [ListEntity] {
lists = results
}
} catch {
fatalError("There was an error fetching the list!")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return lists.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ListCell") as! ListTableViewCell
let list = lists[indexPath.row]
cell.configurationWithSetup(list)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("DetailsSegue", sender: self)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "DetailsSegue" {
let destinationVC = segue.destinationViewController as! DetailsTableViewController
let indexPath : NSIndexPath = self.tableView.indexPathForSelectedRow!
print(indexPath.row) // Print the Row selected to console
// Place the code to pass data here?
// destinationVC.lists = lists[indexPath.row]
// Warning cannot assign value of type 'ListEntity' to type '[ListEntity]'
}
}
}
listTableViewCell
import UIKit
class ListTableViewCell: UITableViewCell {
#IBOutlet weak var titleLabel: UILabel!
func configurationWithSetup(list: AnyObject) {
titleLabel.text = list.valueForKey("title") as! String?
}
}
detailsTableViewController
import UIKit
import CoreData
class DetailsTableViewController: UITableViewController {
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var lists = [ListEntity]()
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("DataCell") as! DetailsTableViewCell
let list = lists[indexPath.row]
cell.configurationWithSetup(list)
return cell
}
}
detailsTableViewCell
import UIKit
import CoreData
class DetailsTableViewCell: UITableViewCell {
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var eventLabel: UILabel!
#IBOutlet weak var locationLabel: UILabel!
func configurationWithSetup(list: AnyObject) {
titleLabel.text = list.valueForKey("title") as! String?
eventLabel.text = list.valueForKey("event") as! String?
locationLabel.text = list.valueForKey("location") as! String?
}
}
The warning contains the answer - just change
var lists = [ListEntity]() to
var lists = ListEntity(), or var lists:ListEntity! and when you prepare for segue set that value.
Then you will need to change
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("DataCell") as! DetailsTableViewCell
// as data source is not array you can just you the item you passed
// let list = lists[indexPath.row]
cell.configurationWithSetup(lists)
return cell
}
You should use a static table view if you just want one cell
More info per you current issue
class DetailsTableViewController: UITableViewController {
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var theDetailListEntity:ListEntity!
override func viewDidLoad() {
super.viewDidLoad()
print(theDetailListEntity) // check that you passed it across
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("DataCell") as! DetailsTableViewCell
cell.configurationWithSetup(theDetailListEntity)
return cell
}
}
Don't forget to add prepare for segue in the listTableViewController otherwise theDetailListEntity won't be set... and then it will crash.
Depending on how you set up your segue, it may differ. But this is what you need
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("showMyDetailView", sender: indexPath)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showMyDetailView" {
guard let
vc = segue.destinationViewController as? DetailsTableViewController,
ip = sender as? NSIndexPath else { fatalError() }
let item = lists[ip.row]
vc.theDetailListEntity = item
// set the item in the next VC
tableView.deselectRowAtIndexPath(ip, animated: true)
}
}

Resources