How do I send specific data based on which cell is clicked? - ios

I have a tableview with a bunch of concerts, and when x cell is clicked, I want the artist of that concert to populate the new tableView. Below is the code for the first view controller (the view controller with all the concerts).
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView1: UITableView!
var arrayOfConcerts: [concert] = [concert]()
override func viewDidLoad()
{
super.viewDidLoad()
self.setUpConcerts()
self.tableView1.rowHeight = 145.0
}
func setUpConcerts()
{
var ACL = concert(imageName: "ACL2015.png")
let Landmark = concert(imageName: "Landmark.png")
let BostonCalling = concert(imageName: "BostonCalling.png")
let Lolla = concert(imageName: "Lolla.png")
arrayOfConcerts.append(ACL)
arrayOfConcerts.append(Landmark)
arrayOfConcerts.append(BostonCalling)
arrayOfConcerts.append(Lolla)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayOfConcerts.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = self.tableView1.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomCell
let concerts = arrayOfConcerts[indexPath.row]
cell.setCell(concerts.imageName)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("concertartist", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
}
}
Below is the code for the Artist View Controller (the second
viewcontroller). This tableView should be populated with specific
artists.
How would I go about doing that?
class ArtistConcerts: UIViewController, UITableViewDataSource, UITableViewDelegate {
var arrayOfArtists: [artist] = [artist]()
#IBOutlet weak var tableViewArtists: UITableView!
override func viewDidLoad()
{
super.viewDidLoad()
self.setUpArtists()
}
func setUpArtists()
{
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayOfArtists.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableViewArtists.dequeueReusableCellWithIdentifier("", forIndexPath: indexPath) as! CustomCell
let artists = arrayOfArtists[indexPath.row]
cell.setCell(artists.imageNameArtist)
return cell
}
}

You need to do this in the prepareForSegue method.
let vc = segue!.destinationViewController as! ArtistConcerts
if let rowSelected = tableView.indexPathForSelectedRow()?.row {
vc.arrayOfArtists = artistsPerforming[0]//this is an array
}
then, set whatever data you need to actually populate the tableView in that new view controller. I am not 100% sure on what you are trying to do though. Does my answer make sense?

you can send data once the cell is pressed to another viewcontroller by using didSelectRowAtIndexPath or prepareForSegue or didSelectRowAtIndexPath + prepareForSegue
let's say you are using prepareForSegue, things you will need
the segue identifier name
cast the destinationController to the controller you want to send the data
the indexPath.row where the cell was selected
then set the variable or variables or data structure that should receive data
Create a segue when you pressed CTRL + Drag from your cell into another viewcontroller
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "Name_Of_Segue"
{
let destination = segue.destinationViewController as! NAME_Of_ViewController
let indexPath = mytableview.indexPathForSelectedRow!
let data = arrayOfArtists[indexPath.row]
destination.artist = data
}
mytableview is an IBOutlet from your tableview
artist is a variable that is declared in your destination controller
destination.artist = data this line of code is passing data from the specific cell then send it to your destination cell

Related

How to reload a view-controller after data has been fetched from a network request?

I have a problem and can't seem to fix it after looking at tutorials online and other SO questions with a similar problem, which leaves me to think I've done something wrong/bad practice related in my code.
I have 2 table view controllers.
The first TableViewController is populated from a database, all this works fine. When I click one of the cells it segues to a second TableViewController which also should be populated from a database (depending on what you select in the first VC).
Currently if I click a cell in TVC1 it goes to TVC2 and it's empty, then it I click back within my navigation controller and select something else, it goes back to TVC2 and shows me my first selection. This indicates that TVC2 is being loaded before the network has returned its data from the database.... so, I tried using tableView.reloadData() in various places like viewDidLoad and viewDidAppear, but i just can't seem to get it to work.
Below is both TVC's. I've stuck with MVC design pattern and haven't included the model and severConnection code for each TVC because I don't want to over complicate the post, however if you'd like to see either I will update.
Thanks in advance for any help.
TableViewController1
class MenuTypeTableViewController: UITableViewController, MenuTypeServerProtocol {
//Properties
var cellItems: NSArray = NSArray()
var selectedItem = String()
override func viewDidLoad() {
super.viewDidLoad()
let menuTypeServer = MenuTypeServer()
menuTypeServer.delegate = self
menuTypeServer.downloadItems()
}
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
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell = tableView.cellForRow(at: indexPath)
selectedItem = (selectedCell?.textLabel?.text)!
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "typeItems" {
let destinationVC = segue.destination as? TypeItemsTableViewController
destinationVC?.selectedItem = self.selectedItem
}
}
}
TableViewController2:
class TypeItemsTableViewController: UITableViewController, TypeItemsServerProtocol {
//Properties
var cellItems: NSArray = NSArray()
var selectedItem: String = String()
let typeItemsServer = TypeItemsServer()
override func viewDidLoad() {
super.viewDidLoad()
typeItemsServer.delegate = self
self.typeItemsServer.foodType = self.selectedItem
self.typeItemsServer.downloadItems()
self.tableView.reloadData()
}
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
}
}
Try adding this to TypeItemsTableViewController
override func viewDidLoad() {
super.viewDidLoad()
cellItems = NSArray()//make sure you have the empty array at the start
typeItemsServer.delegate = self
self.typeItemsServer.foodType = self.selectedItem
self.typeItemsServer.downloadItems()
self.tableView.reloadData()
}
and
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
typeItemsServer.delegate = nil
}
Add this at the top
var cellItems: NSArray = NSArray() {
didSet {
tableview.reloadData()
}
}
Now you can remove other tableview.reloadData() calls since it will automatically be called once cellItems are set...
I think you have a timing problem. You're reloading right after your async data call. You reload but your data isn't in place at that time. Try using functions with escaping or use "didSet" on your data like:
var dataArray: [type] {
didSet {
tableview.reloadData()
}
}

Editing table row cell swift 3

I am trying to edit the table row cell. I have different tableViewController set up to display/edit the current events when they touch on the displayed events from initial tableViewController. Whenever I edit an event and hit save, it goes back to the main viewController where i am initially displaying my events, but it doesn't display the edited events. it keeps showing the original events.
Here is the portion of my main tableView file where i am displaying my events:
class EventsTable: UIViewController, UITableViewDataSource, UITableViewDelegate {
var tableData = ViewController()
#IBOutlet weak var table: UITableView!
#IBAction func saveToMainViewController (change:UIStoryboardSegue) {
let editViewController = change.source as! EditEventsTableViewController
let index = editViewController.index
let titleString = editViewController.editedTitle
tableData.eventsArray[index!].title = titleString
table.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return tableData.eventsArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomeCell
cell.eventTitle.text = tableData.eventsArray[indexPath.row].title
cell.eventLocation.text = tableData.eventsArray[indexPath.row].location
cell.eventDateAndTime.text = tableData.eventsArray[indexPath.row].date
return cell
}
//function to delete cell and saves it
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
tableData.eventsArray.remove(at: indexPath.row)
table.reloadData()
let savedEvents = NSKeyedArchiver.archivedData(withRootObject: tableData.eventsArray)
UserDefaults.standard.set(savedEvents, forKey: "savedEvents")
UserDefaults.standard.synchronize()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "edit" {
var path = table.indexPathForSelectedRow
let detailViewController = segue.destination as! EditEventsTableViewController
detailViewController.index = path?.row
detailViewController.eventsArray = tableData.eventsArray
}
}
Here is the other tableViewController where i edit my data
class EditEventsTableViewController: UITableViewController {
#IBOutlet weak var txtEditTitle: UITextField!
var index:Int!
var eventsArray = [Event]()
var editedTitle: String!
override func viewDidLoad() {
super.viewDidLoad()
txtEditTitle.text = eventsArray[index!].title
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 0 && indexPath.row == 0 {
txtEditTitle.becomeFirstResponder()
}
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "save" {
editedTitle = txtEditTitle.text
}
}
}
incase you guys need a better look at the project,
download link for the project
Probably in EditEventsTableViewController you missed table view reloading?
override func viewDidLoad() {
super.viewDidLoad()
tableView.reloadData()
txtEditTitle.text = eventsArray[index!].title
}
It's unclear, where do you provide data for EditEventsTableViewController. Is it static table view, designed in storyboard?

How to change the label of a different view controller when selecting data from a tableviewcontrollerin Swift 3 / xCode 8?

I have a view controller which is used as a table view. From the table view I wish to select an item from the rows available and once selected I wish for that chosen thing to be the name of a label in a second view controller.
So
tableViewController - select an item from the list in the table
secondViewcontroller - label name is what is selected in the tableViewController
I have looked around and there is talk of using NSNotification but I can't seem to get it to work, in addition to using prepareForSegue.
My relevant code for the tableViewContrller is this:
//MARK Table View
//number of sections the table will have
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
//number of rows each section of the table will have
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return peripheralArray.count
}
//the way the data will be displayed in each row for the sections
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let BluetoothNaming = peripheralArray[indexPath.row].peripheral.name
cell.textLabel?.text = BluetoothNaming
return cell
}
//what happens when we select an item from the bluetooth list
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
stopScanning()
peripheral = peripheralArray[(indexPath as NSIndexPath).row].peripheral
print ("connecting to peripheral called \(peripheral)")
//store the name of the connected peripeheral
let connectedPeripheral = peripheral
manager?.connect(connectedPeripheral!, options: nil)
performSegue(withIdentifier: "segueBackwards", sender: nil)
}
My secondViewController does not have much on its just the label:
import UIKit
class HomepageViewController: UIViewController {
#IBOutlet var ConnectionLabel: UILabel!
func changeBlueoothLabel() {
self.ConnectionLabel.text = "aaaa"
}
}
What do I need to do so that when I select a row in the table that the label in the secondViewController changes its label to reflect it.
Furthermore, if I wanted to change it so that I have another label on the secondViewController and I wanted to change it from disconnected to connected, would there be much more work involved?
Many thanks
to pass data add a string variable in the HomepageViewController and implement prepareForSegue method to pass selected name from tableViewController to HomepageViewController
in HomepageViewController
var selectedName: String?
in tableViewController:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showHomePage" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let peripheral = peripheralArray[indexPath.row].peripheral.name
let homeController = segue.destination as! HomepageViewController
homeController.selectedName = peripheral
}
}
in HomepageViewController
import UIKit
class HomepageViewController: UIViewController {
#IBOutlet var ConnectionLabel: UILabel!
var selectedName: String?
override func viewDidLoad() {
super.viewDidLoad()
// Used the text from the First View Controller to set the label
if let name = selectedName {
ConnectionLabel.text = name
}
}
}

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

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.

Resources