Search code examples
iosswiftuitableviewuistoryboardsegue

Update initialized Data in array with variable then pass array to next view controller


I'm having issues moving the data from the selected cells from the (service2viewcontroller) to the (confirmorderviewcontroller). I am trying to move the cell data (cells with a stepper.value above 0(var quantity > 0.0 (in Service2ViewController))), I was told to pass the array to the next view controller, to do so for a stepper value above 0 I would need to also send the indexpath.row for the rows with a quantity variable above 0 correct? I don't know how to do this if anyone can help I would greatly appreciate it. also the label is not updating when I use the stepper it stays at 0, can I place the quantity variable inside of the array? the total price label in the view controller continues to function and the data is sent to the (confirmorderviewcontroller) with no issues.

first TableView (data is input and forwarded)

class Service2ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var service2Total: UILabel!

@IBOutlet weak var service2TableView: UITableView!

// service data
var Wash: [Service2] = []

//stepper and price calculation
var quantity = Double()

var totalPrice : Double = 0.0
var priceList = [Int : Double]()
var totalProductPrice = [Int : Double]()
var label : Int!
override func viewDidLoad() {
    super.viewDidLoad()

    Wash = Options2()

    if Int(quantity) > 0{
        service2TableView.reloadData()
    }

        priceList[0] = 3.51//price list
        priceList[1] = 5.51


   service2Total.text = "$0.00"

}

// create data array
func Options2() -> [Service2]{

    var washOptions: [Service2] = []

    let option1 = Service2(titled: "Test", pricing: "$3.51", image: #imageLiteral(resourceName: "Wash&Fold"), description:"Testing the description box", quantity: Int(quantity))
    let option2 = Service2(titled: "Test", pricing: "$5.51", image: #imageLiteral(resourceName: "Wash&Fold"), description: "Testing the description box", quantity: Int(quantity))

    washOptions.append(option1)
    washOptions.append(option2)

    return washOptions
}
func numberOfSections(in tableView: UITableView) -> Int {

    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return Wash.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let Wash1 = Wash[indexPath.row]
    let cell = tableView.dequeueReusableCell(withIdentifier: "Service2Cell", for: indexPath) as! Service2TableViewCell

    cell.setService(Wash: Wash1)



    cell.selectionStyle = .none
    return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return 133
}




@IBAction func stepperAcn(_ sender: UIStepper) {

    //change label value with stepper
    let cellPosition = sender.convert(CGPoint.zero, to: service2TableView)
    let indPath : IndexPath = service2TableView.indexPathForRow(at: cellPosition)!

    quantity = sender.value

    let getCurrentProductPrice : Double = priceList[indPath.row]! * sender.value

    totalPrice = gettingPriceLabel(indPath: indPath, getCurrentProductPrice: getCurrentProductPrice)


    if totalPrice == 0{
        service2Total.text = ("$0.00")
    }
    else{
    service2Total.text = ("$")+String(totalPrice)
    }


    print("total price",totalPrice)
    print("quantity double",quantity)
service2TableView.reloadData()


}
func gettingPriceLabel(indPath: IndexPath, getCurrentProductPrice : Double) -> Double
{

    totalProductPrice[indPath.row] = getCurrentProductPrice

    var totalCost : Double = 0.0

    let valuesArr = Array(totalProductPrice.values)

    for i in 0..<valuesArr.count
    {
        totalCost = totalCost + valuesArr[i]
    }
    return totalCost
}
// add function to collect (didSelectRowAt) and send selected data to cart and prepare for segue
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {



}
// change sender to
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let DestViewController: ConfirmorderViewController = segue.destination as! ConfirmorderViewController


    if totalPrice > 0.00{
    DestViewController.amount = totalPrice
    }
}
}

service initializer

 class Service2
{
var service2Title: String
var service2Image: UIImage
var Service2Pricing: String
var service2Description: String
var service2Quantity: Int


init(titled: String, pricing: String, image: UIImage, description: String, quantity: Int){
    self.service2Title = titled
    self.Service2Pricing = pricing
    self.service2Image = image
    self.service2Description = description
    self.service2Quantity = quantity
}
}

Service 2 TableViewCell

class Service2TableViewCell: UITableViewCell {
@IBOutlet weak var service2Title: UILabel!

@IBOutlet weak var service2Stepper: UIStepper!
@IBOutlet weak var service2StepperLbl: UILabel!
@IBOutlet weak var service2Pricing: UILabel!
@IBOutlet weak var service2Image: UIImageView!
@IBOutlet weak var service2Description: UILabel!

func setService(Wash: Service2){
    service2Image.image = Wash.service2Image
    service2Pricing.text = Wash.Service2Pricing.description
    service2Title.text = Wash.service2Title
    service2Description.text = Wash.service2Description
    service2StepperLbl.text = Wash.service2Quantity.description
}
override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

}

Second TableView (receives data)

 class ConfirmorderViewController: UIViewController{



@IBOutlet weak var Total: UILabel!
@IBOutlet weak var confirmOrderTableView: UITableView!



var titled = [String]()
var amount: String = ""
//var quantity = String()
var image1 = [UIImage]()
var Price = [Double]()



override func viewDidLoad() {
    super.viewDidLoad()

    Total.text = amount


    confirmOrderTableView.reloadData()
}

}
extension ConfirmorderViewController: UITableViewDataSource, UITableViewDelegate{

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return titled.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "ConfirmOrderTableViewCell") as! ConfirmOrderTableViewCell

    cell.coTitle?.text = titled[indexPath.row]
    cell.coImg?.image = image1[indexPath.row]
    //cell.coQuantity.text = quantity
    cell.coPrice?.text = Price.description

    return cell
}


}

Solution

  • I have tried here. I got list of row numbers having more than 0 order. I have it stored in whichRowToBeAdd. If user decreased to Zero, respective rows will removed from this array.

    With the help of Singleton Class, we can store whatever we need to show in NextViewController

    var whichRowToBeAdd = [Int]() // GLOBAL
    
    @IBAction func stepperAcn(_ sender: UIStepper) {
    
    //change label value with stepper
    let cellPosition = sender.convert(CGPoint.zero, to: service2TableView)
    let indPath : IndexPath = service2TableView.indexPathForRow(at: cellPosition)!
    
    
        if Int(sender.value) == 0
        {
            if whichRowToBeAdd.contains(indPath.row)
            {
                whichRowToBeAdd.remove(at: whichRowToBeAdd.index(of: indPath.row)!)
            }
            else
            {
    
            }
        }
        else
        {
            if whichRowToBeAdd.contains(indPath.row)
            {
    
            }
            else
            {
                whichRowToBeAdd.append(indPath.row)
            }
        }
    
    //.... 
    //..... Your Code in your answer
    
    
    }
    
    // After stepper Action, final click of Button, which moves to Next ViewController
    @IBAction func goToConfirmOrder(_ sender: UIBarButtonItem) { 
    
        print("\n\n Val_    ", whichRowToBeAdd)
    
        singleTon.sharedInstance.orderDict.removeAll()
    
        for i in 0..<whichRowToBeAdd.count
        {
            let indPath = IndexPath(row: whichRowToBeAdd[i], section: 0)
    
            let newCell = tblVw.cellForRow(at: indPath) as! Service2TableViewCell
            print("qweqwe      ",newCell.testLbl.text)
    
            let name : String = newCell.service2Title.text!
            let image : UIImage = newCell.service2Image.image
            let quantity : Int = Int(newCell.service2StepperLbl.text!)!
    
            getOrderOneByOne(productName: name, productImage: image, productQuantity: quantity)
    
            if i == (whichRowToBeAdd.count - 1)
            {
                self.performSegue(withIdentifier: "confirmOrderVC", sender: nil)
            }
        }
    
    }
    
    func getOrderOneByOne(productName: String, productImage : UIImage, productQuantity: Int)
    {
    
    
        let createDict = ["productName" : productName, "productImage" : productImage, "productQuantity" : productQuantity] as [String : Any]
    
        singleTon.sharedInstance.orderDict.append(createDict)
    
    }
    

    Singleton Class

    class singleTon: NSObject {
    
        static let sharedInstance = singleTon() // Singleton Instance
    
        var orderDict = [[String : Any]]() // Dictionary Declaration
    }
    

    Next ViewController

    class ConfirmOrderViewController: UIViewController {
       override func viewDidLoad() {
         super.viewDidLoad()
    
         print("\n\norderDict.coun    ", singleTon.sharedInstance.orderDict)
       }
    }
    

    With this, you can display datas in TableView in this ConfirmOrderViewController.