didSelectRowAtIndexPath performSegueWithIdentifier = i get nil in target view - ios

i have ThirdView in my "start" view
import Foundation
import UIKit
class ThirdView : UITableViewController {
var jsonz:NSArray = ["Ray Wenderlich"];
var valueToPass : String?;
var programVar : String?;
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
var newProgramVar = "lol";
let destinationVC = segue.destinationViewController as! FourthView
destinationVC.programVar = newProgramVar
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.jsonz.count;
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let myCell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
myCell.textLabel?.text = self.jsonz[indexPath.row] as? String;
return myCell;
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let valueToPass = "asd";
let destinationVC = FourthView()
destinationVC.valuePassed = valueToPass;
self.performSegueWithIdentifier("restDetail", sender: tableView);
}
}
I have a segue identifier: restDetail
When i run a project and click on cell, i cant recieve a variable valuePassed in "second" view, i get nil. Please help, why?
But i normal recieve a variable programVar from function prepareForSegue, it is ok. I have only problem with didSelectRowAtIndexPath segue.
It is my FourthView:
import UIKit
class FourthView: UIViewController {
var valuePassed:String!
var programVar:String!
override func viewDidLoad() {
super.viewDidLoad()
println(valuePassed);
println(programVar);
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
See here what i have in output:
nil
lol
nil
lol
And second question: why in output it shows 4 times?
Sorry for my english.

In didSelectRowAtIndexPath you are not initializing the FourthView instance correctly.
This line:
let destinationVC = FourthView()
Creates a random instance of FourthView, that isn't the one you're using as destination.
If you want to pass a value to the FourthView it's usually best to do that in prepareForSegue.
As you can see in the line below, here you are setting the destinationVC variable to FourthView instance, which is the destination View Controller of your segue.
let destinationVC = segue.destinationViewController as! FourthView

The issue is with the following code:
let valueToPass = "asd";
let destinationVC = FourthView()
destinationVC.valuePassed = valueToPass;
You are allocating a temporary instance of FourthView and passing data to it. And after that you perform a segue. Perform segue initialises your view controller and loads it to the view (different one, not the one you initialised manually in the didSelectRowAtIndexPath). You need to pass the data from the prepareForSegue: method.

Related

Pass the myCell.textLabel?.text value via a segue in a dynamic prototype

I'm trying to segue from one UITableView to another UITableView. I want to segue and pass the myCell.textLabel?.text value of the selected cell to the second UITableView.
The code for my first UITableView (MenuTypeTableViewController and the code for my second UITableView (TypeItemsTableViewController) is also below.
I'm fully aware this involves the prepareForSegue function which currently I've not created, purely because I'm unsure where I override it and how to pass in the textLabel value to it.
Hope my question makes sense, I will update with suggestions and edits.
class MenuTypeTableViewController: UITableViewController, MenuTypeServerProtocol {
//Properties
var cellItems: NSArray = NSArray()
var menuType: MenuTypeModel = MenuTypeModel()
override func viewDidLoad() {
super.viewDidLoad()
let menuTypeServer = MenuTypeServer()
menuTypeServer.delegate = self
menuTypeServer.downloadItems()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier: String = "cellType"
let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
let item: MenuTypeModel = cellItems[indexPath.row] as! MenuTypeModel
myCell.textLabel?.text = item.type
return myCell
}
func itemsDownloaded(items: NSArray) {
cellItems = items
tableView.reloadData()
}
}
class TypeItemsTableViewController: UITableViewController, TypeItemsServerProtocol {
//Properties
var cellItems: NSArray = NSArray()
var typeItemList: TypeItemsModel = TypeItemsModel()
override func viewDidLoad() {
super.viewDidLoad()
let typeItemsServer = TypeItemsServer()
typeItemsServer.delegate = self
typeItemsServer.downloadItems()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier: String = "cellTypeItem"
let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
let item: TypeItemsModel = cellItems[indexPath.row] as! TypeItemsModel
myCell.textLabel?.text = item.name
return myCell
}
func itemsDownloaded(items: NSArray) {
cellItems = items
tableView.reloadData()
}
}
Hi try the following set of code, I have added few additional changes in your code make use of it, I hope it will solve your issue.
I have added only the extra codes which you needed
class TypeItemsTableViewController: UITableViewController, TypeItemsServerProtocol {
// Add this variable in this class and use it whereever you needed it in this class
var selectedItem: String?
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Get the selected cell
let selectedCell = tableView.cellForRow(at: indexPath)
// Now maintain the text which you want in this class variable
selectedItem = selectedCell?.textLabel?.text
// Now perform the segue operation
performSegue(withIdentifier: "TypeItemsTableViewController", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "TypeItemsTableViewController" {
let destinationVC = segue.destination as? TypeItemsTableViewController
destinationVC?.selectedItem = self.selectedItem // Pass the selected item here which we have saved on didSelectRotAt indexPath delegate
}
}
In Second class:
class TypeItemsTableViewController: UITableViewController, TypeItemsServerProtocol {
// Add this variable in this class and use it whereever you needed it in this class
var selectedItem: String?
What you can do is to make a variable in your second UITableView
var String: labelSelected?
then in you prepare for segue method just set the labelSelected to the value of the cell.
refToTableViewCell.labelSelected = youCell.textlabel?.text
If you set up a segue in storyboards from one storyboard to another, you can use the code below in your prepareForSegue method. You'll need to add a testFromMenuTableViewController property to your TypeItemsTableViewController.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? TypeItemsTableViewController,
let path = self.tableView.indexPathForSelectedRow,
let cell = self.tableView.cellForRow(at: path),
let text = cell.textLabel?.text {
destination.textFromMenuTypeTableViewController = text
}
}
For more info check this SO answer.

viewDidLoad() not running after segue

I'm performing a segue from one table view to another.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
NSLog("You selected cell number: \(indexPath.row)!")
self.performSegue(withIdentifier: "types", sender: productList[indexPath.row])
}
It should run the viewDidLoad() of the new TableView described by the custom class of the ViewController (Which I've declared in Storyboard)
func viewDidLoad(parent: String) {
print("This should print")
super.viewDidLoad()
//self.typeTableView.delegate = self
//self.typeTableView.dataSource = self
//Set reference
ref = Database.database().reference()
//Retrieve posts
handle = ref?.child(parent).observe(.childAdded, with: { (snapshot) in
let product = snapshot.key as? String
if let actualProduct = product
{
self.productList.append(actualProduct)
self.typeTableView.reloadData()
}
})
}
Any Idea why this might be happening?
Embed navigation controller to your destination controller
and make a segue from current table views cell to it with identifier types.
Then add below method after your
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "types" {
if let indexPath = tableView.indexPathForSelectedRow {
let object = productList[indexPath.row] as! yourProductType
let controller = (segue.destination as! UINavigationController).topViewController as! YourDestinationViewController
controller.yourProductProperty = object
}
}
}
Make sure to declare yourProductProperty in your Destination controller so that you can access current product object in it.
viewDidLoad has no parameters and needs an override clause:
override func viewDidLoad() {
...
}
Your method signature is
func viewDidLoad(parent: String) {
but it should be
override func viewDidLoad() {
super.viewDidLoad()
// Your code
}
are you using same class to tableviewcell ? if yes then keep different identifier [RESUE IDENTIFIER] for both tableview.

How to access override func tableView property from prepareForSegue method inside same class

I have two viewControllers.First one is a tableViewController and second one is a webViewController.I want to pass data from 1st vc to 2nd vc using segue. For this reason i wants the value of "chosenCellIndex" from override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) to prepareForSegue method. But i can not access the chosenCellIndex value from prepareForSegue method. Please help.
class NewsTableViewController: UITableViewController {
#IBOutlet var Alphacell: UITableView!
var chosenCellIndex = 0
//var temp = 0
var newspaper = ["A","B","C"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return newspaper.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Alphacell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = newspaper[indexPath.row]
// Alphacell.tag = indexPath.row
//Alphacell.addTarget(self, action: "buttonClicked:",forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
chosenCellIndex = indexPath.row
//println(chosenCellIndex)
// Start segue with index of cell clicked
//self.performSegueWithIdentifier("Alphacell", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let secondViewController = segue.destinationViewController as WebViewController
secondViewController.receivedCellIndex = chosenCellIndex
println(chosenCellIndex)
}
}
In order to get chosen cell index you need to get indexpath for selected row, then you need to get section or row index from indexpath.
See the below code for getting row index
let indexPath = tableName.indexPathForSelectedRow
let section = indexPath?.section
let row = indexPath?.row
Make sure you have set the identifier on the segue in storyboard then do:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "someIdentifier"{
let secondViewController = segue.destinationViewController as? WebViewController
//Also, make sure this is the name of the ViewController you are perfoming the segue to.
secondViewController.receivedCellIndex = chosenCellIndex
print(chosenCellIndex)
}
}
Also, what version of Xcode and Swift are you using? println() is now just print().
best way to do that is from did select row function, that example
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let objects = newspaper[indexPath.row]
let vc = storyboard.instantiateViewControllerWithIdentifier("someViewController") as! UIViewController
vc.someString = objects.title
self.presentViewController(vc, animated: true, completion: nil)
}
and prepareForSegue use this code :
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let path = self.tableView.indexPathForSelectedRow()!
segue.destinationViewController.detail = self.detailForIndexPath(path)
}

Swift 2.1 - How to pass index path row of collectionView cell to segue

From the main controller that I have integrated collection view, I want to pass selected cell index path to another view controller (detail view)
so I can use it for updating a specific record.
I have the following working prepareForSegue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "RecipeDetailVC" {
let detailVC = segue.destinationViewController as? RecipeDetailVC
if let recipeCell = sender as? Recipe {
detailVC!.recipe = recipeCell
}
}
}
And I've tried including let indexPath = collection.indexPathForCell(sender as! UICollectionViewCell) but I get Could not cast value of type 'xxx.Recipe' (0x7fae7580c950) to 'UICollectionViewCell' at runtime.
I also have performSegueWithIdentifier("RecipeDetailVC", sender: recipeCell) and I wonder if I can use this to pass the selected cell's index path but not sure I can add this index to the sender.
I am not clear about the hierarchy of your collectionViewCell. But I think the sender maybe not a cell. Try to use
let indexPath = collection.indexPathForCell(sender.superView as! UICollectionViewCell)
or
let indexPath = collection.indexPathForCell(sender.superView!.superView as! UICollectionViewCell)
That may work.
I've wrote up a quick example to show you, it uses a tableView but the concept is the same:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var things = [1,2,3,4,5,6,7,8] // These can be anything...
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let objectForCell = self.things[indexPath.row] // Regular stuff
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let objectAtIndex = self.things[indexPath.row]
let indexOfObject = indexPath.row
self.performSegueWithIdentifier("next", sender: indexOfObject)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "next" {
// On this View Controller make an Index property, like var index
let nextVC = segue.destinationViewController as! UIViewController
nextVC.index = sender as! Int
}
}
}
Here you can see you get the actual object itself and use it as the sender in the perform segue method. You can access it in prepareForSegue and assign it directly to a property on the destination view controller.

unexpected found nil on the line tableView.datasourse = self

I have a navigationController and I have added a custom UIBarButtonItem. What I want to do is when the user tap my button , it present a viewController which has a tableView inside it.
For that ,I have written this :
let shopoingCarVC:shopingCartProductsList = shopingCartProductsList()
self.navigationController?.pushViewController(shopoingCarVC, animated: true)
shopingCartProductsList is my ViewController I intended to navigate to and when It navigate to that It gave me unexpected found nil error at this line :
tableViewProducts.dataSource = self
I have done it before on my other viewControllers but I got this problem when navigating without segue and with using pushViewController mehod.
This is my targetViewCOntroller :
import UIKit
import Alamofire
import Haneke
class shopingCartProductsList: BaseViewController ,UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var ShopingCartProducts: UITableView!
var products = dataService.instance.shopingCartProduct
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
}
override func viewDidLoad() {
super.viewDidLoad()
ShopingCartProducts.dataSource = self
ShopingCartProducts.delegate = self
self.view.backgroundColor = COLOR_BACKGROUND
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let tblCell = tableView.dequeueReusableCellWithIdentifier("shopingCart_cell") as? shopingCart_cell {
if let prod = products[indexPath.row] as? productMD{
tblCell.configCell(prod)
}
return tblCell
}else{
return shopingCart_cell()
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("products count \(products.count)")
return products.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
}
What's wrong ?
Use are wrong while pushing viewcontroller user below code.
let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("LoginViewController") as LoginViewController self.navigationController?.pushViewController(secondViewController, animated: true)
Set identifier in Identity inspector.

Resources