Swift tableview cell doesn't save the state with different identifierCustom UITableViewCell changing indexPath While Scrolling?Can I use a single prototype cell in multiple tableViews?UITableViewCell: Dynamic Cell Height by 'Cell Identifier'How to detect tableView cell touched or clicked in swiftTableView not displaying text with JSON data from API callcannot convert value of type [Struct] to type [string] in coercion swiftHow to use a label on a tableview cell only IF an indexPath object is availableNest a UIScrollView in SwiftPutting different custom cell types in a tableviewSwift vertical UICollectionView inside UITableView

/api/sitecore is not working in CD server

In the Seventh Seal why does Death let the chess game happen?

Is it possible to spoof an IP address to an exact number?

How to reclaim personal item I've lent to the office without burning bridges?

Is there a way to change the aspect ratio of a DNG file?

Find max number you can create from an array of numbers

Can a USB hub be used to access a drive from 2 devices?

The Purpose of "Natu"

How can I effectively map a multi-level dungeon?

What do I need to see before Spider-Man: Far From Home?

Sci-fi book (no magic, hyperspace jumps, blind protagonist)

Are "confidant" and "confident" homophones?

Was the 45.9°C temperature in France in June 2019 the highest ever recorded in France?

Why does mean tend be more stable in different samples than median?

Did Stalin kill all Soviet officers involved in the Winter War?

Will Jimmy fall off his platform?

How come a desk dictionary be abridged?

How frequently do Russian people still refer to others by their patronymic (отчество)?

Is there a standard definition of the "stall" phenomena?

Does the Milky Way orbit around anything?

PhD: When to quit and move on?

Is it acceptable that I plot a time-series figure with years increasing from right to left?

What is the highest level of accuracy in motion control a Victorian society could achieve?

How do I check that users don't write down their passwords?



Swift tableview cell doesn't save the state with different identifier


Custom UITableViewCell changing indexPath While Scrolling?Can I use a single prototype cell in multiple tableViews?UITableViewCell: Dynamic Cell Height by 'Cell Identifier'How to detect tableView cell touched or clicked in swiftTableView not displaying text with JSON data from API callcannot convert value of type [Struct] to type [string] in coercion swiftHow to use a label on a tableview cell only IF an indexPath object is availableNest a UIScrollView in SwiftPutting different custom cell types in a tableviewSwift vertical UICollectionView inside UITableView






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am very confused on the reuse of the cells.



I have a table, each cell is a cell with a switch on it. If I toggle a switch I set the background color of that cell to a different color. However every time I scroll these changes don't persist.



I am subclassing UITalbeViewCell to create my own custom cell. Each cell has a different identifier. However when I scroll through the table, whatever changes I made to the cell still doesn't save. I've read similar questions but none of them worked.. Some suggested subclass which I did, some suggested use different identifier which I also did...



Here is the code of my tableview.



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
let key = Array(dataSource[indexPath.section].keys)[indexPath.row]

let cell = CellWithSwitch.init(style: .subtitle, reuseIdentifier: key)
cell.awakeFromNib()

let val = Array(dataSource[indexPath.section].values)[indexPath.row]
cell.switchView?.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)

if let index = key.firstIndex(of: ".")
cell.textLabel?.text = String(key.suffix(from: key.index(index, offsetBy: 1)))
else
cell.textLabel?.text = key;

cell.switchView?.setOn(val, animated: true)
return cell










share|improve this question






















  • 1) Use a subclass 2) Reuse the cell 3) Never call awakeFromNib yourself. 4) You have to save the state of the switch in the dataSource 5) Use a callback closure rather than target/action.

    – vadian
    Mar 25 at 19:59












  • @vadian subclass of tableviewCell? I am already subclassing it... what is the reuse identifier for if it's still reusing it even with different identifiers?

    – Anna
    Mar 25 at 20:01











  • What is the purpose of different identifiers for the same kind of cell?

    – vadian
    Mar 25 at 20:02











  • @vadian oh so it's actually for each kind..I thought it meant for each instance.

    – Anna
    Mar 25 at 20:04











  • No, it's for each kind. Design the cell in Interface Builder, assign the identifier and use dequeueReusableCell. But the actual issue is that you don't save the state of the switch in the data source and update it in cellForRow.

    – vadian
    Mar 25 at 20:07


















0















I am very confused on the reuse of the cells.



I have a table, each cell is a cell with a switch on it. If I toggle a switch I set the background color of that cell to a different color. However every time I scroll these changes don't persist.



I am subclassing UITalbeViewCell to create my own custom cell. Each cell has a different identifier. However when I scroll through the table, whatever changes I made to the cell still doesn't save. I've read similar questions but none of them worked.. Some suggested subclass which I did, some suggested use different identifier which I also did...



Here is the code of my tableview.



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
let key = Array(dataSource[indexPath.section].keys)[indexPath.row]

let cell = CellWithSwitch.init(style: .subtitle, reuseIdentifier: key)
cell.awakeFromNib()

let val = Array(dataSource[indexPath.section].values)[indexPath.row]
cell.switchView?.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)

if let index = key.firstIndex(of: ".")
cell.textLabel?.text = String(key.suffix(from: key.index(index, offsetBy: 1)))
else
cell.textLabel?.text = key;

cell.switchView?.setOn(val, animated: true)
return cell










share|improve this question






















  • 1) Use a subclass 2) Reuse the cell 3) Never call awakeFromNib yourself. 4) You have to save the state of the switch in the dataSource 5) Use a callback closure rather than target/action.

    – vadian
    Mar 25 at 19:59












  • @vadian subclass of tableviewCell? I am already subclassing it... what is the reuse identifier for if it's still reusing it even with different identifiers?

    – Anna
    Mar 25 at 20:01











  • What is the purpose of different identifiers for the same kind of cell?

    – vadian
    Mar 25 at 20:02











  • @vadian oh so it's actually for each kind..I thought it meant for each instance.

    – Anna
    Mar 25 at 20:04











  • No, it's for each kind. Design the cell in Interface Builder, assign the identifier and use dequeueReusableCell. But the actual issue is that you don't save the state of the switch in the data source and update it in cellForRow.

    – vadian
    Mar 25 at 20:07














0












0








0








I am very confused on the reuse of the cells.



I have a table, each cell is a cell with a switch on it. If I toggle a switch I set the background color of that cell to a different color. However every time I scroll these changes don't persist.



I am subclassing UITalbeViewCell to create my own custom cell. Each cell has a different identifier. However when I scroll through the table, whatever changes I made to the cell still doesn't save. I've read similar questions but none of them worked.. Some suggested subclass which I did, some suggested use different identifier which I also did...



Here is the code of my tableview.



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
let key = Array(dataSource[indexPath.section].keys)[indexPath.row]

let cell = CellWithSwitch.init(style: .subtitle, reuseIdentifier: key)
cell.awakeFromNib()

let val = Array(dataSource[indexPath.section].values)[indexPath.row]
cell.switchView?.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)

if let index = key.firstIndex(of: ".")
cell.textLabel?.text = String(key.suffix(from: key.index(index, offsetBy: 1)))
else
cell.textLabel?.text = key;

cell.switchView?.setOn(val, animated: true)
return cell










share|improve this question














I am very confused on the reuse of the cells.



I have a table, each cell is a cell with a switch on it. If I toggle a switch I set the background color of that cell to a different color. However every time I scroll these changes don't persist.



I am subclassing UITalbeViewCell to create my own custom cell. Each cell has a different identifier. However when I scroll through the table, whatever changes I made to the cell still doesn't save. I've read similar questions but none of them worked.. Some suggested subclass which I did, some suggested use different identifier which I also did...



Here is the code of my tableview.



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
let key = Array(dataSource[indexPath.section].keys)[indexPath.row]

let cell = CellWithSwitch.init(style: .subtitle, reuseIdentifier: key)
cell.awakeFromNib()

let val = Array(dataSource[indexPath.section].values)[indexPath.row]
cell.switchView?.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)

if let index = key.firstIndex(of: ".")
cell.textLabel?.text = String(key.suffix(from: key.index(index, offsetBy: 1)))
else
cell.textLabel?.text = key;

cell.switchView?.setOn(val, animated: true)
return cell







swift uitableview






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 25 at 19:48









AnnaAnna

1612 silver badges15 bronze badges




1612 silver badges15 bronze badges












  • 1) Use a subclass 2) Reuse the cell 3) Never call awakeFromNib yourself. 4) You have to save the state of the switch in the dataSource 5) Use a callback closure rather than target/action.

    – vadian
    Mar 25 at 19:59












  • @vadian subclass of tableviewCell? I am already subclassing it... what is the reuse identifier for if it's still reusing it even with different identifiers?

    – Anna
    Mar 25 at 20:01











  • What is the purpose of different identifiers for the same kind of cell?

    – vadian
    Mar 25 at 20:02











  • @vadian oh so it's actually for each kind..I thought it meant for each instance.

    – Anna
    Mar 25 at 20:04











  • No, it's for each kind. Design the cell in Interface Builder, assign the identifier and use dequeueReusableCell. But the actual issue is that you don't save the state of the switch in the data source and update it in cellForRow.

    – vadian
    Mar 25 at 20:07


















  • 1) Use a subclass 2) Reuse the cell 3) Never call awakeFromNib yourself. 4) You have to save the state of the switch in the dataSource 5) Use a callback closure rather than target/action.

    – vadian
    Mar 25 at 19:59












  • @vadian subclass of tableviewCell? I am already subclassing it... what is the reuse identifier for if it's still reusing it even with different identifiers?

    – Anna
    Mar 25 at 20:01











  • What is the purpose of different identifiers for the same kind of cell?

    – vadian
    Mar 25 at 20:02











  • @vadian oh so it's actually for each kind..I thought it meant for each instance.

    – Anna
    Mar 25 at 20:04











  • No, it's for each kind. Design the cell in Interface Builder, assign the identifier and use dequeueReusableCell. But the actual issue is that you don't save the state of the switch in the data source and update it in cellForRow.

    – vadian
    Mar 25 at 20:07

















1) Use a subclass 2) Reuse the cell 3) Never call awakeFromNib yourself. 4) You have to save the state of the switch in the dataSource 5) Use a callback closure rather than target/action.

– vadian
Mar 25 at 19:59






1) Use a subclass 2) Reuse the cell 3) Never call awakeFromNib yourself. 4) You have to save the state of the switch in the dataSource 5) Use a callback closure rather than target/action.

– vadian
Mar 25 at 19:59














@vadian subclass of tableviewCell? I am already subclassing it... what is the reuse identifier for if it's still reusing it even with different identifiers?

– Anna
Mar 25 at 20:01





@vadian subclass of tableviewCell? I am already subclassing it... what is the reuse identifier for if it's still reusing it even with different identifiers?

– Anna
Mar 25 at 20:01













What is the purpose of different identifiers for the same kind of cell?

– vadian
Mar 25 at 20:02





What is the purpose of different identifiers for the same kind of cell?

– vadian
Mar 25 at 20:02













@vadian oh so it's actually for each kind..I thought it meant for each instance.

– Anna
Mar 25 at 20:04





@vadian oh so it's actually for each kind..I thought it meant for each instance.

– Anna
Mar 25 at 20:04













No, it's for each kind. Design the cell in Interface Builder, assign the identifier and use dequeueReusableCell. But the actual issue is that you don't save the state of the switch in the data source and update it in cellForRow.

– vadian
Mar 25 at 20:07






No, it's for each kind. Design the cell in Interface Builder, assign the identifier and use dequeueReusableCell. But the actual issue is that you don't save the state of the switch in the data source and update it in cellForRow.

– vadian
Mar 25 at 20:07













1 Answer
1






active

oldest

votes


















0














You can change array value in switchChange action



lets i take array for switch as below:



var arrSwitch = [false,false,false,false,false,false,false,false,false,false]


Below is my cellForRowAt Method



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
let cell = tableView.dequeueReusableCell(withIdentifier: "customCell") as! customCell
cell. switchView.setOn(self.arrSwitch[indexPath.row], animated: false)
cell. switchView.tag = indexPath.row
cell. switchView.addTarget(self, action: #selector(self.onSwitchTap(_:)), for: .valueChanged)
return cell



Here is my onSwitchTap Action



@IBAction func onSwitchTap(_ sender: UISwitch) 
self.arrSwitch[sender.tag] = !self.arrSwitch[sender.tag]



Now on scroll it will persist last changes you have done.






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55345379%2fswift-tableview-cell-doesnt-save-the-state-with-different-identifier%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    You can change array value in switchChange action



    lets i take array for switch as below:



    var arrSwitch = [false,false,false,false,false,false,false,false,false,false]


    Below is my cellForRowAt Method



    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
    let cell = tableView.dequeueReusableCell(withIdentifier: "customCell") as! customCell
    cell. switchView.setOn(self.arrSwitch[indexPath.row], animated: false)
    cell. switchView.tag = indexPath.row
    cell. switchView.addTarget(self, action: #selector(self.onSwitchTap(_:)), for: .valueChanged)
    return cell



    Here is my onSwitchTap Action



    @IBAction func onSwitchTap(_ sender: UISwitch) 
    self.arrSwitch[sender.tag] = !self.arrSwitch[sender.tag]



    Now on scroll it will persist last changes you have done.






    share|improve this answer



























      0














      You can change array value in switchChange action



      lets i take array for switch as below:



      var arrSwitch = [false,false,false,false,false,false,false,false,false,false]


      Below is my cellForRowAt Method



      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
      let cell = tableView.dequeueReusableCell(withIdentifier: "customCell") as! customCell
      cell. switchView.setOn(self.arrSwitch[indexPath.row], animated: false)
      cell. switchView.tag = indexPath.row
      cell. switchView.addTarget(self, action: #selector(self.onSwitchTap(_:)), for: .valueChanged)
      return cell



      Here is my onSwitchTap Action



      @IBAction func onSwitchTap(_ sender: UISwitch) 
      self.arrSwitch[sender.tag] = !self.arrSwitch[sender.tag]



      Now on scroll it will persist last changes you have done.






      share|improve this answer

























        0












        0








        0







        You can change array value in switchChange action



        lets i take array for switch as below:



        var arrSwitch = [false,false,false,false,false,false,false,false,false,false]


        Below is my cellForRowAt Method



        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
        let cell = tableView.dequeueReusableCell(withIdentifier: "customCell") as! customCell
        cell. switchView.setOn(self.arrSwitch[indexPath.row], animated: false)
        cell. switchView.tag = indexPath.row
        cell. switchView.addTarget(self, action: #selector(self.onSwitchTap(_:)), for: .valueChanged)
        return cell



        Here is my onSwitchTap Action



        @IBAction func onSwitchTap(_ sender: UISwitch) 
        self.arrSwitch[sender.tag] = !self.arrSwitch[sender.tag]



        Now on scroll it will persist last changes you have done.






        share|improve this answer













        You can change array value in switchChange action



        lets i take array for switch as below:



        var arrSwitch = [false,false,false,false,false,false,false,false,false,false]


        Below is my cellForRowAt Method



        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
        let cell = tableView.dequeueReusableCell(withIdentifier: "customCell") as! customCell
        cell. switchView.setOn(self.arrSwitch[indexPath.row], animated: false)
        cell. switchView.tag = indexPath.row
        cell. switchView.addTarget(self, action: #selector(self.onSwitchTap(_:)), for: .valueChanged)
        return cell



        Here is my onSwitchTap Action



        @IBAction func onSwitchTap(_ sender: UISwitch) 
        self.arrSwitch[sender.tag] = !self.arrSwitch[sender.tag]



        Now on scroll it will persist last changes you have done.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 26 at 7:11









        Kaushik MakwanaKaushik Makwana

        1,2641 gold badge7 silver badges23 bronze badges




        1,2641 gold badge7 silver badges23 bronze badges


















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55345379%2fswift-tableview-cell-doesnt-save-the-state-with-different-identifier%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript