I'm trying to pass a value from one view controller to another. As i tested this is ok and runs with my code. But i have a problem when i'm trying to take cell label value. I tried everything i found on google and stackoverflow, but there is no answer on this. I added a comment on code which says // I THINK THE PROBLEM IS ON THE NEXT LINE OF CODE to help you find where i'm stuck.
My code:
import UIKit
class PlacesTableViewController: UITableViewController {
#IBOutlet weak var placesTableView: UITableView!
var places = [Places]()
var valueToPass:String!
let cellIdentifier = "PlacesTableViewCell"
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
// Table view cells are reused and should be dequeued using a cell identifier.
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? PlacesTableViewCell else {
fatalError("The dequeued cell is not an instance of PlacesTableView Cell.")
}
let place = places[indexPath.row]
cell.placeLabel.text = place.name
cell.ratingControl.rating = place.rating
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
print("You selected cell #\(indexPath.item)!")
let indexPath = placesTableView.indexPathForSelectedRow
// I THINK THE PROBLEM IS ON THE NEXT LINE OF CODE
let currentCell = placesTableView.cellForRow(at: indexPath!)! as UITableViewCell
print(currentCell.detailTextLabel?.text ?? "Failed to use Cell Label")
valueToPass = currentCell.detailTextLabel?.text ?? "Failed to use Cell Label"
performSegue(withIdentifier: "ShowCommentsTableViewController", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "ShowCommentsTableViewController") {
// initialize new view controller and cast it as your view controller
let viewController = segue.destination as! CommentsTableViewController
// will be stored in passedValue on the CommentsTableViewController
viewController.passedValue = valueToPass
//print (viewController.passedValue ?? "")
}
}
}
Why don't you just use the raw value from the data store like you do in the cellForRowAt?
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let place = places[indexPath.row]
valueToPass = place.name
performSegue(withIdentifier: "ShowCommentsTableViewController", sender: self)
}
Replace your didselect method with the given below
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let place = places[indexPath.row]
valueToPass = place.name
performSegue(withIdentifier: "ShowCommentsTableViewController", sender: self)
}
There are two basic issues in your current code, first you are casting your cell into UITableViewCell instead of PlacesTableViewCell and the second issue is that you are accessing detailTextLabel which is not available in your custom cell instead of using placeLabel. The correct code will be like that:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
print("You selected cell #\(indexPath.item)!")
let indexPath = placesTableView.indexPathForSelectedRow
// I THINK THE PROBLEM IS ON THE NEXT LINE OF CODE
let currentCell = placesTableView.cellForRow(at: indexPath!)! as PlacesTableViewCell
print(currentCell. placeLabel?.text ?? "Failed to use Cell Label")
valueToPass = currentCell. placeLabel?.text ?? "Failed to use Cell Label"
performSegue(withIdentifier: "ShowCommentsTableViewController", sender: self)
}
And if you dont want to go through this hassle , you can simply get the values from the original array like that:
let place = places[indexPath.row]
valueToPass = place.name
Related
I am making an app where you create memories into a tableView and you tap on a cell and it takes you to its designated VC, I am trying to make it so that when the cell is tapped, the text from inside that table cell is taken into the label in the next VC. This works but the problem is that when the view is first opened, the text doesn't appear inside the label, even though the console says that the text has loaded correctly:
TableView with a test cell in it.
First time the VC for the cell is opened
Console saying that the text has transferred and loaded correctly
Second time the VC is opened.
Here is my transferring and loading code for the ViewControllers:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
var selectedRow : Int = 0 + 1
var selectedNameVC : String?
var favourites: [NSManagedObject] = []
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
//MARK:- New CoreData methods
let favMemory = favourites[indexPath.row]
cell.textLabel?.text = favMemory.value(forKeyPath: "name") as? String
if #available(iOS 13.0, *) {
cell.backgroundColor = UIColor.secondarySystemGroupedBackground
} else {
// Fallback on earlier versions
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
selectedRow = indexPath.row
let cell = tableView.cellForRow(at: indexPath)
let favMemory = cell?.textLabel?.text
selectedNameVC = favMemory
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? FavouritesViewController {
destination.row = selectedRow
destination.selectedName = selectedNameVC
}
}
class FavouritesViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextFieldDelegate, UITextViewDelegate {
var selectedName: String?
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
labelText.text = selectedName
if labelText.text == "" as String? {
print("Title has not loaded correctly.")
} else {
print("Title has loaded correctly.")
}
}
First, you shouldn't get values from cells... get them from your data source (which is what you used to set the values).
So, in didSelectRowAt instead of:
let cell = tableView.cellForRow(at: indexPath)
let favMemory = cell?.textLabel?.text
you should do:
let favMemory = favourites[indexPath.row]
However, that's not what's causing your issue.
I'm assuming in your Storyboard you have a "Show Segue" connected from your prototype cell to your FavouritesViewController. If that's the case, prepare(for segue: ...) is called before didSelectRowAt. To confirm this, change your code to:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
selectedRow = indexPath.row
// don't do this
//let cell = tableView.cellForRow(at: indexPath)
//let favMemory = cell?.textLabel?.text
let favMemory = favourites[indexPath.row]
print("In didSelectRowAt --- Setting var selectedNameVC = favMemory: \(favMemory)")
selectedNameVC = favMemory
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? FavouritesViewController {
print("In prepareForSegue --- Setting selectedName in FavouritesViewController = selectedNameVC: \(selectedNameVC)")
destination.row = selectedRow
destination.selectedName = selectedNameVC
}
}
This is what you should see in the debug console:
In prepareForSegue --- Setting selectedName in FavouritesViewController = selectedNameVC: nil
In didSelectRowAt --- Setting var selectedNameVC = favMemory: Test
Title has loaded correctly.
As you see, prepareForSegue runs first, so the value of selectedNameVC is nil (it hasn't been set yet).
To fix this, you could set your variables in willSelectRowAt instead of in didSelectRowAt:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
selectedRow = indexPath.row
let favMemory = favourites[indexPath.row]
selectedNameVC = favMemory
return indexPath
}
Alternatively, create your Segue in Storyboard, but do not connect it to the cell. Instead, give it an Identifier (such as "ShowFavourites"), and in didSelectRowAt, set your vars and call performSegue:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
selectedRow = indexPath.row
let favMemory = favourites[indexPath.row]
selectedNameVC = favMemory
performSegue(withIdentifier: "ShowFavourites", sender: nil)
}
How to make Each Cell open the specific view for its indexpath.
In tableview didselect what should i do to make each cell open as its own indexpath so each cell have a different data in the next view
i am tryin when click in a cell in the tableview the next view present it self with it's own data as the next view contain a uitextview like in note app
what should i apply at row didselect
// MARK: -TableFunctions
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return SavingTasks.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let newtask = self.SavingTasks[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
cell.TheLabel?.text = newtask
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if(editingStyle == .delete)
{
self.SavingTasks.remove(at: indexPath.row)
self.TasksTable.deleteRows(at: [indexPath], with: .fade)
GetData()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let NewIndex = self.SavingTasks[indexPath.row]
let view = self.storyboard?.instantiateViewController(withIdentifier: "TaskDetail") as! TaskDetail
view.SavingDetails = [NewIndex]
view.Index = indexPath.row
self.navigationController?.pushViewController(view, animated: true)
}
next class should be appeared
class TaskDetail: UIViewController {
var Delegate: NoteDetailDelegate!
var SavingDetails = [String]()
var Index: Int?
#IBOutlet weak var TaskDetailsFiled: UITextView!
#IBAction func SaveTDF(_ sender: UIButton) {
UserDefaults.standard.set(TaskDetailsFiled.text, forKey: "Saved")
self.navigationController?.popViewController(animated: true)
}
You can use a segue and prepare(for:sender:) to get the next view controller ready more easily than instantiating the view controller and popping it via code. Official documentation here and a sample app from Apple here
An implementation example:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "mysegue"{
if let nextViewController = segue.destination as? NextViewController{
nextViewController.Index = 2
}
}
}
A highlight from the official doc:
For example, if the segue originated from a table view, the sender parameter would identify the table view cell that the user tapped
If you want to stick with the code implementation, you can call view.myvariable = myvalue in your didSelect
I have a UIView inside a TableViewCell,when users tapped in this UIView,it go to another view controller and pass a data along.
So inside TableViewCellClass I done the following :
I set up a protocol and detected the "Tap" gesture,when user table the UIView.This part is working fine:
protocol MyDelegate : class {
func runThisFunction(myString : String)
}
class MyTableViewCell: UITableViewCell {
weak var delegate : MyDelegate?
...other code here
//here detect the tap
let tap = UITapGestureRecognizer(target: self, action: #selector(hereTapped))
self.myUIElementInThisCell.addGestureRecognizer(tap)
}
#objc func hereTapped(sender: UITapGestureRecognizer? = nil){
self.delegate?.runThisFunction(myString: "I am a man")
}
So in my view controller which contain this TableView,I done the following :
I extend out the MyDelegate as subclass,and then attach the protocol function inside it as below
class MyViewController: UIViewController,MyDelagate{
func runThisFunction(myString : String) {
print("Tapped in view controller")
self.performSegue(withIdentifier: "MySegue",sender : self)
}
override func viewDidLoad() {
super.viewDidLoad()
let tableViewCell = MyTableViewCell()
tableViewCell.delegate = self
}
}
Result:
After done all the stuff above,when I tapped the UIView,it didnt perform the segue as stated in MyViewControllerClass,even the print() command also didnt execute.
So what I missing out? Please give me a solution.Thanks
The problem is that the delegate for MyTableViewCell instances is not defined.
When you do:
override func viewDidLoad() {
super.viewDidLoad()
let tableViewCell = MyTableViewCell()
tableViewCell.delegate = self
}
You are setting a delegate for an object that will be destroyed just when the method viewDidLoad() finishes.
Solution 1
In order to avoid this, you have to set the delegate inside the cellForRow method.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath) as! MyTableViewCell
cell.delegate = self
// Other configurations
return cell
}
Solution 2
You can also use the UITableViewDelegate methods in order to capture the user interaction with the cells.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
self.performSegue(withIdentifier: "MySegue",sender : self)
}
This way you avoid all the MyDelegate protocol thing. This would be my preferred option.
The problem is that these 2 lines:
let tableViewCell = MyTableViewCell()
tableViewCell.delegate = self
are not related to the shown cells in the table , it's a cell created on the fly so
set delegate in cellForRow for the cell that you will actually waiting a delegate trigger from them
cell.delegate = self
like this
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = areaSettTable.dequeueReusableCell(withIdentifier:cellID) as! MyTableViewCell
cell.delegate = self
}
Problem is in your viewDidLoad:
// you create a new cell
let tableViewCell = MyTableViewCell()
// set its delegate
tableViewCell.delegate = self
// and then the cell is not used for anything else
Basically you are not setting the delegate for the cells that are being presented, but for another instance that you create in viewDidLoad.
You have to set a delegate in cellForRowAt to make sure the proper cells get the delegate set:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "yourIdentifier", for: indexPath) as! MyTableViewCell
cell.delegate = self
return cell
}
This will set the delegate for those cells, that are presented.
Alternatively, I would recommend using didSelectRowAt from UITableViewDelegate (if your MyViewController implements it):
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 { // only if it is the first cell (I assume that MyTableViewCell is first)
runThisFunction(myString: "I am a man")
}
}
Delegation in not very good here, indeed if you want to change object that didn't passed to the cell explictitly.
My advice is to use closure:
typealias CellTapHandler = (String)->()
class CustomCell: UITableViewCell {
var handler: CellTapHandler?
#objc func hereTapped(sender: UITapGestureRecognizer? = nil) {
handler?("String or whatever you want to get back from cell.")
}
//...
}
and set up it from view controller
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "yourIdentifier", for: indexPath)
(cell as? MyTableViewCell).handler = { [weak self] string in }
return cell
}
PS: As I said, usually you want to pass object related to cell further. It's difficult to do with delegation, as you had to pass to cell some additional token, to determine object by the cell, o pass object itself breaking Model-View separation paradigm. But it can be done easily with closures:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let object = self.myData[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "yourIdentifier", for: indexPath)
(cell as? MyTableViewCell).handler = { [weak self] string in
self.performSegue(withIdentifier: "MySegue",sender : object)
}
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (let myObj = sender as? MyObjType, let subsequentVC = segue.destination as? NextViewController) {
subsequentVC.selectedMyObject = myObj
}
}
I have a TableView that when the user clicks it needs to show a detail view displaying the name of the row it clicked. I populate the tableView using a Json call but I can't figure out what I'm doing wrong.
This is my bits of code of ViewController
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var valueToPass:String!
#IBOutlet weak var tableView: UITableView!
// Instantiate animals class
var items = [animalObject]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
addDummyData()
}
func addDummyData() {
RestManager.sharedInstance.getRandomUser(onCompletion: {(json) in
if let results = json.array {
for entry in results {
self.items.append(animalObject(json: entry))
}
DispatchQueue.main.sync{
self.tableView.reloadData()
}
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier") as! CustomTableViewCell!
let animal = self.items[indexPath.row]
cell?.label.text = animal.name
return cell! //4.
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You selected cell #\(indexPath.row)!")
// Get Cell Label
// let indexPath = tableView.indexPathForSelectedRow!
var currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell
print(currentCell.textLabel?.text)
valueToPass = currentCell.textLabel?.text
print(valueToPass)
performSegue(withIdentifier: "detailView", sender: indexPath)
}
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
if (segue.identifier == "detailView") {
// initialize new view controller and cast it as your view controller
let viewController = segue.destination as! DetailViewController
// your new view controller should have property that will store passed value
viewController.passedValue = valueToPass
}
}
}
and my detailView only has the following info
#IBOutlet weak var tooPass: UILabel!
var passedValue: String!
override func viewDidLoad() {
super.viewDidLoad()
print("DETAILS")
print(passedValue)
tooPass.text = passedValue
}
I'm not sure if the preparedToSegue is firing a little bit earlier because my terminal looks like this:
I used as a reference the following question any guidance will be appreciated
Try this for didSelectRowAt method.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
valueToPass = self.items[indexPath.row]
print(valueToPass)
performSegue(withIdentifier: "detailView", sender: indexPath)
}
Just pass the entire item in the items array.
Make the DetailViewController's passed item of type item. Then just access item.whateverPropertyRequired.
The problem is that in your cellForRow method, you are casting your cell to CustomTableViewCell type while in your didSelectRow, you are casting it as UITableViewCell. Change
var currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell
in your didSelectRow to
var currentCell = tableView.cellForRow(at: indexPath)! as CustomTableViewCell
Good approach here is to use view model. Create model which contains your items and data associated with them. And at segue pass your data model. It’s bad coding, getting data right from cell on didSelect method, unless some ui working on that cell
This question already has answers here:
Send data from TableView to DetailView Swift
(4 answers)
Closed 5 years ago.
I'm trying to recognize which tableviewcell is selected and after that i want to get the label value of that cell and pass it to the next view controller. My cell has a Label value which is string and a Number value which is Int. I'm using a firebase database to get all that data.
My code:
import UIKit
class PlacesTableViewController: UITableViewController {
//MARK: Properties
#IBOutlet weak var placesTableView: UITableView!
var places = [Places]()
override func viewDidLoad()
{
super.viewDidLoad()
// Loads data to cell.
loadData()
}
override func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
//return the number of rows
return places.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
// Table view cells are reused and should be dequeued using a cell identifier.
let cellIdentifier = "PlacesTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? PlacesTableViewCell else {
fatalError("The dequeued cell is not an instance of PlacesTableView Cell.")
}
let place = places[indexPath.row]
cell.placeLabel.text = place.name
cell.ratingControl.rating = place.rating
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
print(places[indexPath.section])
self.performSegue(withIdentifier: "ShowCommentsTableViewController", sender: nil)
}
}
you can follow this thread to be useful send-data-from-tableview-to-detailview-swift
You have to create variable in destination view controller and store data in those Variable before Moving to Destination View controller.
This link will help you for this.
Try this:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let selectedPlace = places[indexPath.section]
self.performSegue(withIdentifier: "ShowCommentsTableViewController", sender: selectedPlace)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let selectedPlace = sender as? Places,
let destViewController = segue.destination as? SecondViewController {
destViewController.place = selectedPlace
}
}