Krutarth Patel Krutarth Patel - 3 months ago 13
Swift Question

In tableview Data is Overwriting

I have two

collectionView
. One is main and second is sub items
when i click both collectionView the data is added in
tableView
.

My requirement is like when I click on first
collectionView
it will be added in cart and
tableViewCell
should display it original price which I retrieve from web service.

Now when I click on second
collectionView
it should also added to tableview but when I click this it will have to display price as 0.
To add into tableview i am using did select method of
collectionView
:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let dictSub = arr[indexPath.row] as! [String : AnyObject]
//to insert product to top of tableview
arrTable(dictSub, atIndex: 0)
self.tbl.reloadData()
}


At
cellForRowAtIndexPath
method I am checking that
isMainProduct
equals to one or zero

code :

if isFromMain == "1" {
let Price = NSString(string: pPrice1).floatValue
let total = 1 * Price
cell.lbl.text = String(format: "%.2f", total)
} else {
let Price = 0.00
let total = 1 * Price
cell.lbl.text = String(format: "%.2f", total)
}


When one it will add original price but when it is not from main product it will display zero.

Issue is:

First when i click on main collection view original price is displayed but when i clicked on sub items price of main product also changes to zero.

I want to prevent this data overwriting.

Answer

In your didSelectItemAtIndexPathyou are adding Dictionaryto Array, you can use this Dictionary to differentiate that it is coming from main collectionView or not instead of setting instance value of isFromMain to 1.

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    var  dictSub = arr[indexPath.row] as! [String : AnyObject]  
    if collectionView == mainCollectionView {
        dictSub["isFromMain"] = "1"
    }
    else {
        dictSub["isFromMain"] = "0"
    }
    arrTable(dictSub, atIndex: 0)
    self.tbl.reloadData()
}

Now use this key to in cellForRowAtIndexPath to check it is coming from main CollectionView or from second one.

let dic = arrTable[indexPath.row] as! [String : AnyObject]
let isFromMain = dic["isFromMain"] as! String
if  isFromMain == "1" {
    let Price   = NSString(string: pPrice1).floatValue
    let total   = 1 * Price
    cell.lbl.text = String(format: "%.2f", total)
} else {
    let Price   = 0.00
    let total   = 1 * Price
    cell.lbl.text = String(format: "%.2f", total)
}
Comments