navigationItem.title from UITableViewCell - ios

Navigation Bar title is not appearing according to the Selected Cell.
I have the Navigation View Controller inside a Container View.
The Container View is in ViewController.
ViewController:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "embedseg" {
guard let splitViewController = segue.destination as? UISplitViewController,
let leftNavController = splitViewController.viewControllers.first as? UINavigationController,
let masterViewController = leftNavController.topViewController as? MasterViewController,
//let detailViewController = splitViewController.viewControllers.last as? DetailViewController
let rightNavController = splitViewController.viewControllers.last as? UINavigationController,
let detailViewController = rightNavController.topViewController as? DetailViewController
else { fatalError() }
let firstMonster = masterViewController.monsters.first
detailViewController.monster = firstMonster
masterViewController.delegate = detailViewController
detailViewController.navigationItem.leftItemsSupplementBackButton = true
detailViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
//detailViewController.navigationItem.title = "Hello" <-- tested this, it worked.
//detailViewController.navigationItem.title = cell.textLabel?.text <-- this didn't work.
//detailViewController.navigationItem.title = monster.name <-- and this didn't work.
}
}
MasterViewController:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let monster = monsters[indexPath.row]
cell.textLabel?.text = monster.name
return cell
}

When you select the cell
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! YourCellClassName
self.performSegue(withIdentifier: "embedseg", sender:cell.textLabel?.text)
}
in prepareforSegue
let cellText = sender as! String
detailViewController.navigationItem.title = cellText

This happens because monster and cell are defined inside
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {}
but not inside
override func prepare(for segue: UIStoryboardSegue, sender: Any?){}
If you have set your segues using the storyboard you can do something like this:
override func prepare(for segue: UIStoryboardSegue, sender: Any?){
if let cell = sender as? UITableViewCell {
detailViewController.navigationItem.title = cell.textLabel?.text
}
}
or something like this:
override func prepare(for segue: UIStoryboardSegue, sender: Any?){
if let cell = sender as? UITableViewCell {
let indexPath = tableView.indexPath(for: cell)
detailViewController.navigationItem.title = monsters[indexPath.row].name
}
}
In the first case you cast "sender" as the cell so you can access it's values, in the second case you cast "sender" as the cell, you find what is it's indexPath and then you use the indexPath to find the correct "monster" using you array monsters

Related

TableViewCell to ViewController - Swift

I tried many ways but still can't go to another ViewController. This is my storyboard.
and This is my code.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? HistoryMainTableViewCell {
listItems.sort() { $0.seq > $1.seq }
let history = listItems[indexPath.row]
cell.setValue(history: history)
return cell
} else {
return HistoryMainTableViewCell()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "vcProductHistory" {
if let productHistoryPage = segue.destination as? HistoryProductViewController {
if let IndexPath = tableViewHistory.indexPathForSelectedRow {
let historyArray = listItems[IndexPath.row]
productHistoryPage.history = historyArray
}
}
}
}
Try this code:(Untested Code)
Note: Below code will trigger prepare segue. When, tableViewCell selected.Let me know the code works...
func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
// let indexPath = myTableView!.indexPathForSelectedRow
// let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell
//sendSelectedData = (currentCell.textLabel?.text)! as String as NSString
performSegue(withIdentifier: "vcProductHistory", sender: self)
}
Based on your answer to my initial comment: dragging the line from initial vc to destination vc tells your vc about the segue, preparing for segue tells your vc what do when the segue is triggered, but you still need to let your vc know when it should perform the segue. try this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? HistoryMainTableViewCell else { return HistoryMainTableViewCell() }
let history = listItems[indexPath.row]
cell.setValue(history: history)
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "vcProductHistory" {
guard let productHistoryPage = segue.destination as? HistoryProductViewController, let indexPath = sender as? IndexPath else { return }
let historyArray = listItems[indexPath.row]
productHistoryPage.history = historyArray
}
}
func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
performSegue(withIdentifier: "vcProductHistory", sender: indexPath)
}
I think this is a little bit neater using the guard syntax. Also, it uses sender as the indexPath, not using tableView.indexPathForSelectedRow.
Also, I noticed you have this in your cellForRowAtIndexPath:
listItems.sort() { $0.seq > $1.seq }
Your sorting your data source in cellForRowAtIndexPath. You can't do that there because that function gets called for each row individually. You need to do the sorting before that is called, somewhere like viewWillAppear. Also, to sort an array in place you need to remove the () after sort. try this.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
listItems.sort { $0.0.seq > $0.1.seq }
tableView.reloadData()
}
I think you should connect to UINavigationController , not to HistoryProductionViewController
Because your MainViewController's segue connected to Navigation Controller
I guess in func prepareForSegue segue.identifier == "vcProductHistory" it works but, if let productHistoryPage = segue.destination as? HistoryProductViewController not works
because your destination ViewController's class is NavigationController
you should call
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "vcProductHistory" {
if let naviVC = segue.destination as? UINavigationController {
if let productHistoryPage = naviVC.topViewController as? HistoryProductViewController {
if let IndexPath = tableViewHistory.indexPathForSelectedRow {
let historyArray = listItems[IndexPath.row]
productHistoryPage.history = historyArray
}
}
}
}
}
Your solution - as you described it - should work.
The most work here can be done directly in the Storyboard.
Select the prototype cell in the TableView, drag the Segue to the NavigationController and select presentModally.
This should work without further magic.
When selecting the TableViewCell the NavigationController should be presented. There is also no code needed at this point (except for the population of the TableView).
If not - you maybe misconfigured your TableView by setting the selection to No Selection:
or you set User Interaction Enabled to false somewhere.

Move Text from cell to text label in a different view controller

I have created an app that displays 10 random numbers in a table view. This is the code I used
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ShowNumber", for: indexPath)
// Configure the cell...
cell.textLabel?.text = "\(indexPath.row + 1): \(Int(arc4random_uniform(10001)))"
return cell
}
Now I want to be able to click on one cell and be taken to another view controller and in the center of the page it displays the random number. I have the view controller all set up and linked to the original table view. I'm just having trouble passing my data through the segue. This is what I have so far. I know it unfinished, I just don't know what to do.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showRandomNumber" {
let controller = segue.destination as! ShowNumberTableViewController
let selectedRow = (tableView.indexPathForSelectedRow as NSIndexPath?)?.row ?? 0
controller.LabelText =
}
The LabelText is the name of the label that I want to pass the data to, but I don't know how to
Using the indexPathForSelectedRow, you can get a reference to the cell that triggered the segue. You can then access the textLabel within that cell, get its value, and pass it to the next view controller.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showRandomNumber" {
let controller = segue.destination as! ShowNumberTableViewController
if let indexPath = tableView.indexPathForSelectedRow {
let cell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell
if let textToPass = cell.textLabel.text {
controller.labelText = textToPass
}
}
}
}
Then in ShowNumberTableViewController you want a var labelText and in your viewDidLoad() you can assign it to the textLabel in that view controller with
centerLabel.text = labelText
The way you are doing, the numbers will change when you scroll the table view. I think you should save the numbers in an array.
About how to grab the selected number in the prepareForSegue: I would do this way:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showRandomNumber" {
if let cell = sender as? UITableViewCell, indexPath = tableView.indexPathForCell(cell) {
let selectedNumber = numbers[indexPath.row]
controller.labelText = String(selectedNumber)
}
}
}

UIImage not appearing

When I segue my UIImageView from my NewsTableViewController.swift, the image does not appear in my NewsDetailTableViewController.swift.
Here is an image of my simulator:
Here is an image of my Main.storyboard:
Here is my prepareForSegue() method code:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
if segue.identifier == "showDetail" {
if let indexPath = tableView.indexPathForSelectedRow {
let destinationController = segue.destinationViewController as! NewsDetailTableViewController
destinationController.item = items[indexPath.row]
let newsImage = UIImageView(image: UIImage(named: detailImages[indexPath.row]))
destinationController.image = newsImage
}
}
}
It is also worth mentioning that my image in my NewsTableViewController.swift is set to 0x0, and in my NewsDetailTableViewController.swift, it is set to 600x216. I don't know if this would matter or not. If you desire any code, please do feel free to ask.
FYI, I use Swift.
In prepareForSegue the IBOutlets of your destinationController have not been initialized yet. Just pass detailImages to another array property on NewsDetailTableViewController. Change your prepareForSegue to:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
if segue.identifier == "showDetail" {
if let indexPath = tableView.indexPathForSelectedRow {
let destinationController = segue.destinationViewController as! NewsDetailTableViewController
destinationController.item = items[indexPath.row]
destinationController.imageNames = detailImages
}
}
}
Then in NewsTableViewController add the following code:
var imageNames:[String]?
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//replace with whatever identifier you're using
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell
cell.imageView?.image = self.imageNames[indexPath.row]?
return cell
}

Why is this value not passing between my ViewControllers?

I'm coding a multi-step sign-up flow, but cannot get the cell labels to pass between each viewcontroller.
Here is the code from the first viewController:
class FirstVC: UIViewController, UITableViewDelegate {
#IBOutlet weak var tableview: UITableView!
var userGoalOptions = ["Lose Fat","Gain Muscle", "Be Awesome"]
var selectedGoal: String = ""
override func viewDidLoad() {
super.viewDidLoad()
self.title = "What Is Your Goal?"
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell1")! as UITableViewCell
cell.textLabel?.text = userGoalOptions[indexPath.row]
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userGoalOptions.count
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let indexPath = tableView.indexPathForSelectedRow
let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!
selectedGoal = currentCell.textLabel!.text!
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "secondSeque") {
let vc = segue.destinationViewController as! SecondVC
vc.userGoal = selectedGoal
}
}
The segue (secondSegue) is connected to the table view cell in Interface Builder
In my destination viewcontroller (vc) I have an empty userGoal variable, but when I try to print the contents it returns nothing.
I know variations of this question have been asked numerous times, but I can't seem to find (or maybe understand) what I'm messing up.
Assuming the segue is connected to the table view cell in Interface Builder the cell is passed as the sender parameter in prepareForSegue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "secondSeque") {
let selectedIndexPath = tableView.indexPathForCell(sender as! UITableViewCell)!
let vc = segue.destinationViewController as! SecondVC
vc.userGoal = userGoalOptions[selectedIndexPath.row]
}
In this case didSelectRowAtIndexPath is not needed and can be deleted.
Apart from that it is always the better way to retrieve the data from the model (userGoalOptions) than from the view (the table view cell) for example
Do
let indexPath = tableView.indexPathForSelectedRow
selectedGoal = userGoalOptions[indexPath.row]
Do not
let indexPath = tableView.indexPathForSelectedRow
let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!
selectedGoal = currentCell.textLabel!.text!
The prepareForSegue Should not be part of the table view function, you have copied it into a place where it is never called. Move it out and place a break point on it to see that it is being called.

How to get custom cell label when segue?

I'm trying to get the name of the selected row in the custom cell. How I can do that in Swift?
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var selectedCell = CustomCell()
selectedCell = tableView(tbl, cellForRowAtIndexPath: <#NSIndexPath#>)
if(segue.identifier == "next") {
var next = (segue.destinationViewController as! EngineViewController)
next.titleSub = selectedCell.cell.lblBrand.text
}
}
I believe if you are just selecting a cell, the cell should be the sender. Try this
if let selectedCell = sender as? CustomCell {
if(segue.identifier == "next") {
var next = (segue.destinationViewController as! EngineViewController)
next.titleSub = selectedCell.cell.lblBrand.text
}
}
You could attempt to override didSelectRowAtIndexPath to get your cell.
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as! CustomCell
cell.yourLabel.textYouWant
let yourViewController = storyboard?.instantiateViewControllerWithIdentifier("ViewController") as! ViewController
navigationController?.pushViewController(yourViewController, animated: true)
}

Resources