Send data from TableView to DetailView Swift
Here is the example for you:
var valueToPass:String!
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
println("You selected cell #\(indexPath.row)!")
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRowAtIndexPath(indexPath)! as UITableViewCell
valueToPass = currentCell.textLabel.text
performSegueWithIdentifier("yourSegueIdentifer", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
if (segue.identifier == "yourSegueIdentifer") {
// initialize new view controller and cast it as your view controller
var viewController = segue.destinationViewController as AnotherViewController
// your new view controller should have property that will store passed value
viewController.passedValue = valueToPass
}
}
But don't forget to create a passedValue
variable into your DetailViewController
.
This is just an example of passing data from one viewController to another and you can pass data with this example as you need.
And for more info refer this links.
Passing values between ViewControllers based on list selection in Swift
Use didSelectRowAtIndexPath or prepareForSegue method for UITableView?
Swift: Pass UITableViewCell label to new ViewController
https://teamtreehouse.com/forum/help-swift-segue-with-variables-is-not-working
May be this will help you.
Swift 3.0
var valueToPass:String!
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You selected cell #\(indexPath.row)!")
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell
valueToPass = currentCell.textLabel?.text
performSegue(withIdentifier: "yourSegueIdentifer", sender: self)
}
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
if (segue.identifier == "yourSegueIdentifer") {
// initialize new view controller and cast it as your view controller
var viewController = segue.destination as! AnotherViewController
// your new view controller should have property that will store passed value
viewController.passedValue = valueToPass
}
}
Send data from TableView to DetailView Swift even if it not on UITableList
In your next view controller, create an optional String variable and pass the value "searchController.searchBar.text!". For example, in your prepare method, add below code:
let controller = segue.destination as? medDetailsViewController
controller.searchText = searchController.searchBar.text!
Swift 4: Passing Data from Tableview to ViewController
Your problem seems simple:
var image = [UIImage]() // lost here
That's an ARRAY of images.
Suggest for a single item, you want a single image?
var image:UIImage!
Warning, will crash if image is nil when used. (alternate use UIImage? but must unwrap).
Therereby, in the table view controller..
vc.image = foodImage[indexPath.section][indexPath.row]
Will be behave as expected. No need to use:
self.itemImage.image = UIImage(named: image) //not working!!! Cant seem to find the right code for this from converting UIIMAGE to String. I am just lost!
(Which is incorrect because you're trying to use an array of images to pass to the STRING parameter of load image from file.)
Just use:
self.itemImage.image = self.image
As they are both image types.
You do the correct thing in the cell and index the array within the array to get the image, so do the same here and have a singe image type in your detail view controller. In that way if you click beef, the image for beef is sent.
As an aside, consider using a data model type for your recipe.
class Ingredient {
var name:String = ""
var image:UIImage! = nil
var count:Int = 0
var calories:Int = 0
public init(name: String, image: UIImage, count: Int, calories: Int) {
self.name = name
self.image = image
self.count = count
self.calories = calories
}
}
then you can do say:
let ingredients = [Ingredient("Beef", beefImage, 100, 350), Ingredient("Onion", onionImage, 1, 20)]
or etc,
Pass Data to Detail View by Tapping TableView Cell
From your description it is possible that you have 2 segues. one in the StoryBoard and one in your code.
The prepare method is not performing the segue. it simply gives you a chance to perform actions that are related to the segue, for example pass data to the destinations controller. do not call perform segue if you already created one in the StoryBoard and vice versa.
a common usage of prepare will look like this:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//get the destination controller and cast it to your detail class
if let destinationController = segue.destination as? YourDetailClassHere {
//set the properties you want
destinationController.someProperty = someValue
}
}
Few notes -
- you can use the sender object to pass data from the perform call.
- common mistake is to assume that the destination controller is always your detail controller. it can be the navigation controller and then you will have to extract the detail from the navigation controller.
How can I pass data from collectionView and tableView to detailViewController?
You need to update destination View Controller (MemeDetailViewController) with data you want to pass like in the first example:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "MemeDetailViewController" ,
let nextScene = segue.destination as? MemeDetailViewController ,
let cell = collectionView?.dequeueReusableCell(withReuseIdentifier: "MemeCollectionViewCell", for: IndexPath) {
let selectedMeme = memes[IndexPath]
nextScene.meme = selectedMeme
}
}
How pass data from button in TableViewCell to View Controller?
Function @IBAction func infoButtonAction(_ sender: Any) {}
should be in the ProductListCell
When that button is tapped, connect with the ProductListVC
by delegate
or closure
to get the selected product.
Update
Using delegate:
Update your ProductListCell
import UIKit
import SDWebImage
import Firebase
protocol ProductListCellDelegate: class {
func onTouchInfoButton(from cell: ProductListCell)
}
class ProductListCell: UITableViewCell {
@IBOutlet weak var productImage: UIImageView!
@IBOutlet weak var dispensaryName: UILabel!
@IBOutlet weak var productName: UILabel!
@IBOutlet weak var thcPercent: UILabel!
@IBOutlet weak var cbdPercent: UILabel!
@IBOutlet weak var categoryLabel: UILabel!
@IBOutlet weak var categoryStrain: UILabel!
@IBOutlet weak var moreInfo: RoundButton!
weak var product: Product!
weak var delegate: ProductListCellDelegate?
func configure(withProduct product: ProductList) {
self.product = product
productName.text = "\(String(describing: product.brand)): \(String(describing: product.name))"
dispensaryName.text = product.dispensaryName
categoryLabel.text = product.category
productImage.sd_setImage(with: URL(string: product.imageUrl))
cbdPercent.text = product.cbd
thcPercent.text = product.thc
categoryStrain.text = product.strain
}
@IBAction func infoButtonAction(_ sender: Any) {
self.delegate?.onTouchInfoButton(from: self)
}
}
In your ProductListVC
:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ProductListCell") as?
ProductListCell else { return UITableViewCell() }
cell.configure(withProduct: productSetup[indexPath.row])
cell.delegate = self
return cell
}
extension ProductListVC: ProductListCellDelegate {
func onTouchInfoButton(from cell: ProductListCell) {
let selectedProduct = cell.product
// Do your stuff here
}
}
UPDATE
Because you use segue for navigation so let's create a variable to store your selected product in your ProductListVC
import UIKit
import Firebase
import FirebaseFirestore
class ProductListVC: UIViewController {
@IBOutlet weak var productListTableView: UITableView!
var productInventory: [ProductList] = []
var productSetup: [ProductList] = []
var selectedProduct: Product?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
productListTableView.dataSource = self
productListTableView.delegate = self
searchBar.delegate = self
fetchProducts { (products) in
self.productSetup = products
self.productListTableView.reloadData()
}
}
func fetchProducts(_ completion: @escaping ([ProductList]) -> Void) {
let ref = Firestore.firestore().collection("products")
ref.addSnapshotListener { (snapshot, error) in
guard error == nil, let snapshot = snapshot, !snapshot.isEmpty else {
return
}
completion(snapshot.documents.compactMap( {ProductList(dictionary: $0.data())} ))
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? MoreInforVC {
vc.product = self.selectedProduct
}
}
}
extension ProductListVC: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return productSetup.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ProductListCell") as?
ProductListCell else { return UITableViewCell() }
cell.configure(withProduct: productSetup[indexPath.row])
cell.delegate = self
return cell
}
}
extension ProductListController: ProductListCellDelegate {
func onTouchInfoButton(from cell: ProductListCell) {
self.selectedProduct = cell.product
self.performSegue(withIdentifier: "YourSegueIdentifier", sender: self)
}
}
Related Topics
Computed Read-Only Property VS Function in Swift
How to Check If a Text Field Is Empty or Not in Swift
How to Use Userdefaults With Swiftui
Load Local Web Files & Resources in Wkwebview
JavaScript Synchronous Native Communication to Wkwebview
Any Reason Not Use Use a Singleton "Variable" in Swift
Generic Function Taking a Type Name in Swift
Extra Arguments At Positions #11, #12 in Call Swiftui
"Classname Has No Member Functionname" When Adding Uibutton Target
How to Multiply Two Arrays Element-Wise
How to Dispatch_Sync, Dispatch_Async, Dispatch_After, etc in Swift 3, Swift 4, and Beyond
Error-Handling in Swift-Language
Instantiated Optional Variable Shows as Nil in Xcode Debugger
How to Print the Type or Class of a Variable in Swift