how to pass the value from table view cell to view controller - ios

I have one table view with many cell.Each cell have one image and one label.And what i need is when ever user press any cell it have to go to detail viewcontroller.And there i need to show the respective image and label name in my detail view controller.How to do that.
I have done all segue.But in my detail view controller i have one image and label.Now how can i show the image and label name - when i select the any cell from my table view ??
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet var tableView: UITableView!
var valueToPass:String!
var selectedIndexPath: NSIndexPath = NSIndexPath()
var tableData: [String] = ["Christ Redeemer", "Great Wall of China", "Machu Picchu","Petra","Pyramid at Chichén Itzá","Roman Colosseum","Taj Mahal"]
var arrImageName: [String] = ["ChristRedeemer", "GreatWallOfChina", "MachuPicchu","Petra","PyramidChichenItza","RomanColosseum","TajMahal"]
var tableRate: [String] = ["$120", "$100", "$222","$1000","$500","$900","$2000"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
func numberOfSectionsInTableView(tableView: UITableView) ->Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.tableData.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:CustomTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("CustomTableViewCell") as! CustomTableViewCell
cell.imageVW.image = UIImage(named:self.arrImageName[indexPath.row])
cell.lblName.text = self.tableData[indexPath.row]
cell.rateName.text = self.tableRate[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.selectedIndexPath = indexPath
performSegueWithIdentifier("DetailView", sender: indexPath)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
let indexPath = self.selectedIndexPath
if (segue.identifier == "DetailView") {
var viewController = segue.destinationViewController as! DetailVC
viewController.data = UIImagePNGRepresentation(UIImage(named:self.arrImageName[indexPath.row])!)!
//viewController.name = self.tableData[[indexPath.row]]
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Here is my detailvc.swift
import UIKit
class DetailVC: UIViewController {
var data: NSData = NSData()
var name: String = String()
#IBOutlet weak var ImgView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.ImgView.image = UIImage(data: data)
//self.detailLabelNamee.text = name
}
}

change your did select with something like this
Declare one gloabal indexPath in ViewContrller like this
var selectedIndexPath: NSIndexPath = NSIndexPath()
Change your didselect like this
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.selectedIndexPath = indexPath
self.performSegueWithIdentifier("DetailView", sender: self)
}
Now in prepareForSegue method add this
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
let indexPath = self.selectedIndexPath
if (segue.identifier == "DetailView") {
var viewController = segue.destinationViewController as! DetailVC
viewController.data = UIImagePNGRepresentation(UIImage(named:self.arrImageName[indexPath.row]))
viewController.name = self.tableData[indexPath.row]
}
}
Now add two global identifier in DetailVC like below
var data: NSData = NSData()
var name: String = String()
Now assign this data and string to imageview and label in viewdid load
change the viewdidload of detailVC like this
override func viewDidLoad() {
super.viewDidLoad()
self.ImgView.image = UIImage(data: data)
self.detailLabelNamee.text = name
}
Hop this will help.

In your didSelectRowAtIndexPath you can just perform the segue and in prepareForSegue you can get the indexPath with self.tableView.indexPathForSelectedRow. And of course it returns an optional and you have to check it first for safety. I think this is the easiest way.

In your didSelectRowAtIndexPath you can get the index path of the selected row and then you can performSegue and pass index path in sender.
In prepareForSeque , from the index path , you can get the image , tableData and tableRate . Which you can pass to detail view . Something like below
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("DetailView", sender: indexPath)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
let selectedIndexPath = sender as! NSIndexPath
if (segue.identifier == "DetailView") {
var viewController = segue.destinationViewController as! DetailVC
viewController . setValues(tableData:tableData[selectedIndexPath] , rate: tableRate[selectedIndexPath] , imageName:arrImageName[selectedIndexPath])
}
class DetailVC: UIViewController {
var imageName:String!
var tableData:String!
var tableRate:String!
func setValues(tableData:String , rate:String , imageName:String){
imageName = tableData
tableRate = rate
imageName = imageName
}
or
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
let selectedIndexPath = sender as! NSIndexPath
if (segue.identifier == "DetailView") {
var viewController = segue.destinationViewController as! DetailVC
viewController.imageName = self.arrImageName[selectedIndexPath.row]
viewController.tableData = self.tableData[selectedIndexPath.row]
viewController.tableRate = self.tableRate[selectedIndexPath.row]
}

You can declare a variable for store indexpath in that .
var selectedItemIndex = Int()
on click of cell write below lines in didselectowatndexaPath
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
selectedItemIndex = indexPath.row
self .performSegueWithIdentifier(“YourViewController”, sender: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let yourVC = segue.destinationViewController as! YourViewController
yourVC.text = tableData[selectedItemIndex]
yourVC.image = UIImage(named:arrImageName[selectedItemIndex])
}

You are almost there! The line:
performSegueWithIdentifier("DetailView", sender: self)
needs changing. 'self' is passing a reference of the current view controller to the prepareForSegue method. If you change 'self' to 'indexPath', then prepareForSegue will see the cell index path in the 'sender' object and you take what you want from that.
You could do something like:
if (segue.identifier == "yourSegueIdentifer") {
var viewController = segue.destinationViewController as! DetailVC
let indexPath = sender as! NSIndexPath
viewController.passedImageName = self.arrImageName[indexPath.row]
viewController.passedData = self.tableData[indexPath.row]
viewController.passedRate = self.tableRate[indexPath.row]
and in DetailVC:
class DetailVC: UIViewController {
var passedImageName:String!
var passedData:String!
var passedRate:String!

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.

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)
}

Passing data from table view to textview of view controller

I just found a tutorial how to pass data between two table views to textview of ViewController, its nice but I need an app about passing data from just one table view to textview of ViewController, I'm searching about this little problem but can't find it, hope you guys understand me, here is a pic of app tutorial I founded, I uploaded in tiny pic because can't post it here:
import UIKit
class FirstTableViewController: UITableViewController{
var FirstTableArray = [String]()
var SecondArray = [SecondTable]()
var ThirdArray = [ThirdView]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
FirstTableArray = ["First", "Second", "Third","Fourth"]
SecondArray =
[SecondTable(SecondTitle: ["jdhfhjd","kldjjlkdfjd"]),
SecondTable(SecondTitle: ["FirstSecond","SecondSecond","ThirdSecond"]),
SecondTable(SecondTitle: ["FirstThird","SecondThird","ThirdThird"]),
SecondTable(SecondTitle: ["FirstFourth"])]
ThirdArray = [ThirdView(ThirdViewArray: [lf1,lf2]),
ThirdView(ThirdViewArray: ["asdkljf","asdfasd","asdfas"]),
ThirdView(ThirdViewArray: ["asdkljf","asdfasd","asdfas"]),
ThirdView(ThirdViewArray: ["asdkljf"])]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return FirstTableArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var Cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
Cell.textLabel?.text = FirstTableArray[indexPath.row]
return Cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var indexPath : NSIndexPath = self.tableView.indexPathForSelectedRow()!
var DestViewController = segue.destinationViewController as! SecondTableViewController
var SecondTableArrayTwo : SecondTable
SecondTableArrayTwo = SecondArray[indexPath.row]
DestViewController.SecondArray = SecondTableArrayTwo.SecondTitle
var ThirdAnswerArray : ThirdView
ThirdAnswerArray = ThirdArray[indexPath.row]
DestViewController.SecondAnswerArray = ThirdAnswerArray.ThirdViewArray
}
}
Here is your complete Updated code for one tableView to detailView:
import UIKit
class FirstTableViewController: UITableViewController{
var FirstTableArray = [String]()
var passThisArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// This array will display on your tableviewcell.
FirstTableArray = ["First", "Second", "Third","Fourth"]
//You can pass element of this array
passThisArray = ["element1", "element2", "element3", "element4"]
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return FirstTableArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var Cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
Cell.textLabel?.text = passThisArray[indexPath.row]
return Cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "detailView") {
var vc = segue.destinationViewController as! ViewController
//Get the Index of selected Cell
var indexPath : NSIndexPath = self.tableView.indexPathForSelectedRow()!
//assign string to next view controller instance from selected cell.
vc.FirstString = FirstTableArray[indexPath.row]
}
}
}
And you have to modify many things from your project.
And HERE is your project.

Segue from Custom Data Cell in Swift

I am new to Swift and IOS, I used to have a normal table view and everything worked. I have now implemented a Custom Table view cell and was wondering how to implement my PrepareForSegue method with my UITableView. I want to be able to send the selected Table Cell index to the segue for the next controller to access a certain array position. Right now the sender Object is a CustomCell: UITableViewCell object. can I access the table index from that object or some other way?
//
// ViewController.swift
// OBU Bus Tracker
//
// Created by AJ Norton on 4/20/15.
// Copyright (c) 2015 AJ Norton. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate {
#IBOutlet var table: UITableView!
var locations = [String]()
var overall = Dictionary<String, AnyObject>()
override func viewDidLoad() {
super.viewDidLoad()
// check if the user is running the app for the first time
// if let firstTime = NSUserDefaults.standardUserDefaults().objectForKey("firstTime")
// {
//
// println("second time")
// }
// else
// {
// println("worked")
// NSUserDefaults.standardUserDefaults().setBool(true, forKey: "firstTime")
// }
if let path = NSBundle.mainBundle().pathForResource("busSchedule", ofType: "plist")
{
if let dict = NSDictionary(contentsOfFile: path) as? Dictionary<String, AnyObject>
{
locations = dict.keys.array
overall = dict
}
}
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return locations.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell: CustomRouteViewCell = table.dequeueReusableCellWithIdentifier("Cell") as! CustomRouteViewCell
cell.locationTitle.text = "\(locations[indexPath.row])"
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
println("I was clicked")
performSegueWithIdentifier("routeToTime", sender: indexPath.row)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
//TODO
println("\(sender?.integerValue)")
if segue.identifier == "routeToTime"
{
var ttvc = segue.destinationViewController as! TimeViewController
var s = sender as! CustomRouteViewCell
println("\(s.in)")
var place = s.indentationLevel as! Int
var dicts = overall[locations[place]] as! Dictionary<String,AnyObject>
var arr = dicts["Weekday"] as! [Int]
ttvc.days = dicts
ttvc.times = arr.reverse()
}
}
}
performSegueWithIdentifier("routeToTime", sender: indexPath.row)
you call above method. so in this method:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
the local argument sender is indexPath.row, is NOT a instance of CustomRouteViewCell.
So you can write code:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "routeToTime"
{
var ttvc = segue.destinationViewController as! TimeViewController
var place = sender as! Int
var dicts = overall[locations[place]] as! Dictionary<String,AnyObject>
var arr = dicts["Weekday"] as! [Int]
ttvc.days = dicts
ttvc.times = arr.reverse()
}
}
It is best to write code in the MVC patten, so don't store your data in a tableview cell.
Whateve you want do that, you must set a cell's property(For example: rowIndex: Int) that indicate the indexRow of the data in this method 'func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)'. Your code looks like:
if segue.identifier == "routeToTime"
{
var ttvc = segue.destinationViewController as! TimeViewController
var cell = sender as! CustomRouteViewCell
var place = cell.indexRow
var dicts = overall[locations[place]] as! Dictionary<String,AnyObject>
var arr = dicts["Weekday"] as! [Int]
ttvc.days = dicts
ttvc.times = arr.reverse()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell: CustomRouteViewCell = table.dequeueReusableCellWithIdentifier("Cell") as! CustomRouteViewCell
cell.locationTitle.text = "\(locations[indexPath.row])"
cell.indexRow = ... //Set the index of cell's data.
return cell
}
By the way, the indentationLevel property is:
var indentationLevel: Int // adjust content indent. default is 0
How about storing the cell index as a NSUserDefault and retrieving it from the other side?
That way you can use a generic segue created through the storyboard, implement the table cells on selected function.

Swift : How do I pass the same text and image form tableVC to a detailVC using the same tableviewcell?

I'm trying to pass the same (text + image ) from tableVC to the detail tableVC using an array populated in tableVC.
It is working in tableVC but no data passed into the detailVC.
They share one tableviewcell.
class TableViewCell: UITableViewCell {
#IBOutlet var img: UIImageView!
#IBOutlet var title: UILabel!
}
tableVC
class TableViewController: UITableViewController {
var thecourseName = [String]()
var theimg = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
thecourseName = ["course 1 ","course 2 ","course 3 "]
theimg = [UIImage(named: "109.png")!,UIImage(named: "110.png")!]
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell
// Configure the cell...
cell.title.text = thecourseName[indexPath.row]
cell.date.text = date[indexPath.row]
cell.img.image = UIImage[indexPath.row]
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if ( segue == "toInfo") {
var text = self.tableView.indexPathForSelectedRow()
var detailsVC: DetalisTableViewController = segue.destinationViewController as! DetalisTableViewController
detailsVC.courseName = thecourseName
}
}
One error in `cell.img.image = UIImage[indexPath.row]
detailVC
import UIKit
class DetalisTableViewController: UITableViewController {
var courseName = [String]()
#IBOutlet var passedCourse: UILabel!
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 Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return courseName.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell
// Configure the cell...
cell.title.text = courseName[indexPath.row]
return cell
}
StoryBoard
http://s18.postimg.org/mwkw5hf1l/image.png
To fix your first error change cell.img.image = UIImage[indexPath.row] to cell.img.image = theimg[indexPath.row]
I think there is an issue with this
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if ( segue == "toInfo") {
var text = self.tableView.indexPathForSelectedRow()
var detailsVC: DetalisTableViewController = segue.destinationViewController as! DetalisTableViewController
detailsVC.courseName = thecourseName
}
}
var text = self.tableView.indexPathForSelectedRow() is not text it is an indexPath
and in the scope of this function there is no way that thecourseName is what you expect that it should be. I think what you want is something more along these lines.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if ( segue == "toInfo") {
var text = thecourseName[self.tableView.indexPathForSelectedRow()]
var detailsVC: DetalisTableViewController = segue.destinationViewController as! DetalisTableViewController
detailsVC.courseName = text
}
}
That should give you the text for the selected cell and set it for the variable of the details View.

Resources