简体   繁体   中英

swift passing data from Table View cells with segment to another view controller

I have a problem with passing the data

To make it clear, I will explain the idea of what I worked on, and what is the problem.

The idea is in the first view controller the user will enter the title and description and then chooses from the options of the pop-up button, the options are (exchange, borrow, donation, sell). The data entered will be saved in the option chosen by the user. then the data will be displayed in the second view controller in the table view. If the user chooses the exchange option and enters the data, his data will be displayed in the table view in the exchange (index 0) and this works for me the data is displayed in the table view in the correct form as I want.

The problem I am experiencing is when I pass the data to the other view controller. When the user clicks on any cell, it will pass the same data regardless of the difference in the index. If the user chooses the borrow (index 1) and clicks any cell, it'll display the exchange (index 0) data. No matter what indexes you choose and the cell you click on it will pass the same data!!!!!

first view controller

here I'm entering the data

it's shown in the table view in the right index of the segment no problem with that

after I click it pass the right data

look here if I change the index and click to any cell it will pass the same data!!

look here if I change the index and click to any cell it will pass the same data!!

Here's my code for the first vc

import UIKit
import FirebaseFirestore

class ViewController4: UIViewController {
    @IBOutlet weak var mssglabel: UILabel!
    @IBOutlet weak var selectservice: UIButton!
    @IBOutlet weak var titleTextField: UITextField!
    @IBOutlet weak var descriptionTextField: UITextView!
    @IBOutlet weak var custombtun: UIButton!
    
   
    let db = Firestore.firestore()

    var chooseOption = ""

    override func viewDidLoad() {
        super.viewDidLoad()
       
        setpopupbutn()
        selectservice.layer.cornerRadius = 25
        descriptionTextField.layer.cornerRadius = 25
        custombtun.layer.cornerRadius = 25

    }
    
    @IBAction func containbutn(_ sender: Any) {

            let vc = (storyboard?.instantiateViewController(withIdentifier: "vc3"))!
            navigationController?.pushViewController(vc, animated: true)
           
        
        spcificOption()
      
    }
    

    
    func saveDataDonation() {
        
         if let description = descriptionTextField.text,
            let tittle = titleTextField.text{
            // Save Data to Database
            
            db.collection("userDonationDatabase")
                .addDocument(data: [
                    "description" : description,
                    "BookTitle": tittle ]) {
                    (error) in
                    if let err = error {
                        print(err.localizedDescription)
                    }else {
                        print("تم حفظ البيانات بنجاح")
                        print(description)
                        print(tittle)
                    }
                } // end of closure
            
        }

        
    }
    
    func saveDataSale() {
        
        if let description = descriptionTextField.text,
           let tittle = titleTextField.text{
            // Save Data to Database
            
            db.collection("userSaleDatabase")
                .addDocument(data: [
                    "description" : description,
                    "BookTitle": tittle ]) {
                    (error) in
                    if let err = error {
                        print(err.localizedDescription)
                    }else {
                        print("تم حفظ البيانات بنجاح")
                        print(description)
                        print(tittle) }
                }
        }
        
    }
    
    func saveDataExchange() {
        
        if let description = descriptionTextField.text,
           let tittle = titleTextField.text {
            // Save Data to Database
            
            db.collection("userExchangeDatabase")
                .addDocument(data: [
                    "description" : description,
                    "BookTitle": tittle ]) {
                    (error) in
                    if let err = error {
                        print(err.localizedDescription)
                    }else {
                        print("تم حفظ البيانات بنجاح")
                        print(description)
                        print(tittle) }
                }
        }
        
    }
    
    func saveDataBorrow() {
        
        if let description = descriptionTextField.text,
           let tittle = titleTextField.text {
            // Save Data to Database
            
            db.collection("userBorrowDatabase")
                .addDocument(data: [
                    "description" : description,
                    "BookTitle": tittle]) {
                    (error) in
                    if let err = error {
                        print(err.localizedDescription)
                    }else {
                        print("تم حفظ البيانات بنجاح")
                        print(description)
                        print(tittle) }
                }
        }
        
    }
    
    func setpopupbutn () {
       
        let option = {( ACTION : UIAction ) in
            self.chooseOption = ACTION.title
            print("حفظ الداتا في ",self.chooseOption)}
        selectservice.menu = UIMenu (children : [
            UIAction (title : "تبرع" , state: .on , handler: option),
            UIAction (title : "بيع" ,  handler: option),
            UIAction (title : "تبادل" ,  handler: option),
            UIAction (title : "إستعارة" ,  handler: option),
            
        ])

        
        saveDataDonation()
        selectservice.showsMenuAsPrimaryAction = true
        selectservice.changesSelectionAsPrimaryAction = true
        

    }

    func spcificOption() {
        if chooseOption == ("تبرع") {
            saveDataDonation()
        } else if chooseOption == ("بيع") {
            saveDataSale()
        } else if chooseOption == ("تبادل") {
            saveDataExchange()
        } else if chooseOption == ("إستعارة") {
            saveDataBorrow()
        }
    }

}


and this is the second vc (Table view)

import UIKit
import FirebaseFirestore
import Firebase


class ViewController3: UIViewController, UITableViewDataSource, UITableViewDelegate {

    
    let db = Firestore.firestore()
    var exchange : [exchange] = []
    var borrow : [borrow] = []
    var donation : [donation] = []
    var sale : [sale] = []


    @IBOutlet weak var segmentOutlet: UISegmentedControl!
    @IBOutlet weak var userDataTableView: UITableView!
   
    override func viewDidLoad() {
        super.viewDidLoad()
  
        userDataTableView.dataSource = self
        userDataTableView.delegate = self
        getDataDonation()
        getDataSale()
        getDataExchange()
        getDataBorrow()
        userDataTableView.reloadData()

        
    }
    

    @IBAction func serviceSeg(_ sender: UISegmentedControl) {
       
       if sender.selectedSegmentIndex == 0 {
           getDataExchange()
          
        }
        
        else if sender.selectedSegmentIndex == 1 {
           
            getDataBorrow()
           
            
        }
        else if sender.selectedSegmentIndex == 2 {
           
            getDataDonation()
           
          
        }
        else if sender.selectedSegmentIndex == 3 {
            
            getDataSale()
            
           
        }
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {



        if segmentOutlet.selectedSegmentIndex == 0 {
            return exchange.count
        } else if segmentOutlet.selectedSegmentIndex == 1 {
            return borrow.count
        }else if segmentOutlet.selectedSegmentIndex == 2 {
            return donation.count
        } else if segmentOutlet.selectedSegmentIndex == 3 {
       return sale.count
   }
       return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        if segmentOutlet.selectedSegmentIndex == 0 {
            cell.textLabel?.text = exchange [indexPath.row].passTitle
        } else if segmentOutlet.selectedSegmentIndex == 1 {
            cell.textLabel?.text = borrow [indexPath.row].passTitle
        } else if segmentOutlet.selectedSegmentIndex == 2 {
            cell.textLabel?.text = donation [indexPath.row].passTitle
        } else if segmentOutlet.selectedSegmentIndex == 3 {
            cell.textLabel?.text = sale [indexPath.row].passTitle
        }
        return cell
    }
    
    func getDataDonation(){
        donation.removeAll()
        db.collection("userDonationDatabase")
            .getDocuments { querySnapshot, error in
                if let err = error { print(err.localizedDescription)}
                else {
                    for document in querySnapshot!.documents {
                        let data = document.data()
                        print( data["BookTitle"] as! String )
                        self.donation.append(finalProject.donation(passTitle3:data["BookTitle"] as! String , passDes3: data["description"] as! String))

                    }
                    DispatchQueue.main.async {
                        self.userDataTableView.reloadData()
                    }
                }
            }
    }
   
    func getDataSale(){
        sale.removeAll()
        db.collection("userSaleDatabase")
            .getDocuments { querySnapshot, error in
                if let err = error { print(err.localizedDescription)}
                else {
                    for document in querySnapshot!.documents {
                        let data = document.data()
                        print( data["BookTitle"] as! String )
                        self.sale.append(finalProject.sale(passTitle4:data["BookTitle"] as! String , passDes4: data["description"] as! String))

                        
                    }
                   
                    DispatchQueue.main.async {
                        self.userDataTableView.reloadData()
                    }
                }
            }
    }
    
    func getDataExchange(){
        exchange.removeAll()
        db.collection("userExchangeDatabase")
            .getDocuments { querySnapshot, error in
                if let err = error { print(err.localizedDescription)}
                else {
                    for document in querySnapshot!.documents {
                        let data = document.data()
                        print( data["BookTitle"] as! String )
                        self.exchange.append(finalProject.exchange(passTitle1:data["BookTitle"] as! String , passDes1: data["description"] as! String))
                        

                    }
        
                    DispatchQueue.main.async {
                        self.userDataTableView.reloadData()
                    }
                }
            }
    }
    
    func getDataBorrow(){
        borrow.removeAll()
        db.collection("userBorrowDatabase")
            .getDocuments { querySnapshot, error in
                if let err = error { print(err.localizedDescription)}
                else {
                    for document in querySnapshot!.documents {
                        let data = document.data()
                        print( data["BookTitle"] as! String )
                        self.borrow.append(finalProject.borrow(passTitle2:data["BookTitle"] as! String , passDes2: data["description"] as! String))

                    }
                   
                    DispatchQueue.main.async {
                        self.userDataTableView.reloadData()
                    }
                }
            }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if let vc = storyboard?.instantiateViewController(withIdentifier:"vc10") as? ViewController10 {
            vc.recivedE = exchange[indexPath.row]
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    
}

Note... I tried to do this but it didn't work

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if let vc = storyboard?.instantiateViewController(withIdentifier:"vc10") as? ViewController10 {
            vc.recivedE = exchange[indexPath.row]
            vc.recivedB = borrow[indexPath.row]
            vc.recivedD = donation[indexPath.row]
            vc.recivedS = sale[indexPath.row]
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }

This is the struct, I created a struct for each index


public struct exchange {
      var passTitle : String
      var passDes : String
      init (passTitle1:String, passDes1:String) {
          self.passTitle = passTitle1
          self.passDes = passDes1
      }
}
public struct borrow {
      var passTitle : String
      var passDes : String
      init (passTitle2:String, passDes2:String) {
          self.passTitle = passTitle2
          self.passDes = passDes2
      }
}
public struct donation {
      var passTitle : String
      var passDes : String
      init (passTitle3:String, passDes3:String) {
          self.passTitle = passTitle3
          self.passDes = passDes3
      }
}

public struct sale {
      var passTitle : String
      var passDes : String
      init (passTitle4:String, passDes4:String) {
          self.passTitle = passTitle4
          self.passDes = passDes4
      }
}

this is the last vc



import UIKit
import FirebaseStorage
import Firebase
import FirebaseFirestore
import SDWebImage

class ViewController10: UIViewController {
   
    @IBOutlet weak var userBookTitle: UILabel!
    @IBOutlet weak var userBookDescription: UILabel!
    
    var recivedE:exchange?
    var recivedB:borrow?
    var recivedD:donation?
    var recivedS:sale?
    


    override func viewDidLoad() {
        super.viewDidLoad()
 

     
        userBookTitle.text = recivedE?.passTitle
        userBookDescription.text = recivedE?.passDes

    }
    

}

Note... I tried to do this but it didn't work

    override func viewDidLoad() {
        super.viewDidLoad()

        if let et = recivedE?.passTitle ,
        let ed = recivedE?.passDes{
            userBookTitle.text = et
            userBookDescription.text = ed
        }
        else if let bt = recivedB?.passTitle ,
          let  bd = recivedB?.passDes {
                userBookTitle.text = bt
                userBookDescription.text = bd

            }
        else if let dt = recivedD?.passTitle ,
            let dd = recivedD?.passDes {
                userBookTitle.text = dt
                userBookDescription.text = dd
            }
            else if let st = recivedS?.passTitle ,
                let sd = recivedS?.passDes {
                    userBookTitle.text = st
                    userBookDescription.text = sd
                }
        


    }

and this also not working

    override func viewDidLoad() {
        super.viewDidLoad()

        userBookTitle.text = recivedE?.passTitle
        userBookDescription.text = recivedE?.passDes
        userBookTitle.text = recivedB?.passTitle
        userBookDescription.text = recivedB?.passDes
        userBookTitle.text = recivedD?.passTitle
        userBookDescription.text = recivedD?.passDes
        userBookTitle.text = recivedS?.passTitle
        userBookDescription.text = recivedS?.passDes
    }

help me, please

In both of your numberOfRowsInSection and cellForRowAt functions, you are checking the selected segment index to determine which data to use:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if segmentOutlet.selectedSegmentIndex == 0 {
        return exchange.count
    } else if segmentOutlet.selectedSegmentIndex == 1 {
        return borrow.count
    }else if segmentOutlet.selectedSegmentIndex == 2 {
        return donation.count
    } else if segmentOutlet.selectedSegmentIndex == 3 {
        return sale.count
    }
    return 0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    if segmentOutlet.selectedSegmentIndex == 0 {
        cell.textLabel?.text = exchange [indexPath.row].passTitle
    } else if segmentOutlet.selectedSegmentIndex == 1 {
        cell.textLabel?.text = borrow [indexPath.row].passTitle
    } else if segmentOutlet.selectedSegmentIndex == 2 {
        cell.textLabel?.text = donation [indexPath.row].passTitle
    } else if segmentOutlet.selectedSegmentIndex == 3 {
        cell.textLabel?.text = sale [indexPath.row].passTitle
    }
    return cell
}

However, in didSelectRowAt , you only use the exchange data:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if let vc = storyboard?.instantiateViewController(withIdentifier:"vc10") as? ViewController10 {
        vc.recivedE = exchange[indexPath.row]
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

If you implement the same if / else if structure in didSelectRowAt you should get the desired results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM