Tableview Dynamic switches having issue , if i select the switch and make it on immediately it not getting on in swiftHow to disable uiswitch in custom cell of uitableviewHow to detect tableView cell touched or clicked in swiftExpand and Collapse tableview cellsUpdate or reload UITableView after completion of delete action on detail viewthread 1: exc_bad_instruction(code=exc_1386_invop,subcode=0x0)TableView not displaying text with JSON data from API callcannot convert value of type [Struct] to type [string] in coercion swiftNest a UIScrollView in SwiftSwift vertical UICollectionView inside UITableViewHow to search in Firebase Database Swift

Is there a RAID 0 Equivalent for RAM?

How can I write humor as character trait?

Can I still be respawned if I die by falling off the map?

What happens if you are holding an Iron Flask with a demon inside and walk into an Antimagic Field?

Why is so much work done on numerical verification of the Riemann Hypothesis?

What's the difference between releasing hormones and tropic hormones?

What does "Scientists rise up against statistical significance" mean? (Comment in Nature)

Temporarily disable WLAN internet access for children, but allow it for adults

What exact color does ozone gas have?

Are Captain Marvel's powers affected by Thanos' actions in Infinity War

How does the math work for Perception checks?

Recommended PCB layout understanding - ADM2572 datasheet

Using substitution ciphers to generate new alphabets in a novel

Sums of entire surjective functions

Can a Canadian Travel to the USA twice, less than 180 days each time?

What is going on with 'gets(stdin)' on the site coderbyte?

Why does the Sun have different day lengths, but not the gas giants?

Does an advisor owe his/her student anything? Will an advisor keep a PhD student only out of pity?

Does malloc reserve more space while allocating memory?

Why is it that I can sometimes guess the next note?

Limits and Infinite Integration by Parts

Store Credit Card Information in Password Manager?

Why does AES have exactly 10 rounds for a 128-bit key, 12 for 192 bits and 14 for a 256-bit key size?

Can a College of Swords bard use a Blade Flourish option on an opportunity attack provoked by their own Dissonant Whispers spell?



Tableview Dynamic switches having issue , if i select the switch and make it on immediately it not getting on in swift


How to disable uiswitch in custom cell of uitableviewHow to detect tableView cell touched or clicked in swiftExpand and Collapse tableview cellsUpdate or reload UITableView after completion of delete action on detail viewthread 1: exc_bad_instruction(code=exc_1386_invop,subcode=0x0)TableView not displaying text with JSON data from API callcannot convert value of type [Struct] to type [string] in coercion swiftNest a UIScrollView in SwiftSwift vertical UICollectionView inside UITableViewHow to search in Firebase Database Swift













1















I have created a UITableView and adding the switch dynamically into each cell the basis is of requirement . if i select a switch and turn it on and immediately select next switch and turn it on, it's having an issue with the state of the switch its changing and a previously selected switch is getting off, its happening only if i select all the switch fast.



enter image description here



here is the image in this i am adding all the switches dynamically as per the data and if i on the first switch it data will load them in the other table . but if i select all the switch fast fast and turn them on some switch will stuck in to off state only . if i tap on the outside of the table its disappear and if again i load the table that time i can see all selected and previously enable (on) switch is turn off(not all but random its happen)



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")

if let _ = cell else
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")

if let d = self.data
cell?.textLabel?.text = d[indexPath.row]
let switchView = UISwitch(frame: .zero)
switchView.setOn(self.isFolderIsAdded(folderName: d[indexPath.row]), animated: true)
switchView.tag = indexPath.row // for detect which row switch Changed
switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
cell?.accessoryView = switchView


return cell!


func isFolderIsAdded(folderName:String) -> Bool
for val in listOfSelectedFolder
if(folderName == val )
return true


return false;


@objc func switchChanged(_ sender : UISwitch!)
if let d = self.data
if(sender.isOn)
self.delegate?.selectedSubFolder(name: d[sender.tag])
else
self.delegate?.deleteFilesFromFolder(folderName: d[sender.tag])












share|improve this question
























  • Add else clock in cellForRowAt indexPath and set switchView.setOff and check what Happens.

    – Nikunj Kumbhani
    Mar 7 at 6:47











  • In IOS 12+ simulator have some issue related UI update, Tabbar tapped, button pressed, switch on/off update etc, I have faced the same issue but in the device it works fine, So check this once in the real device.

    – AtulParmar
    Mar 7 at 7:03















1















I have created a UITableView and adding the switch dynamically into each cell the basis is of requirement . if i select a switch and turn it on and immediately select next switch and turn it on, it's having an issue with the state of the switch its changing and a previously selected switch is getting off, its happening only if i select all the switch fast.



enter image description here



here is the image in this i am adding all the switches dynamically as per the data and if i on the first switch it data will load them in the other table . but if i select all the switch fast fast and turn them on some switch will stuck in to off state only . if i tap on the outside of the table its disappear and if again i load the table that time i can see all selected and previously enable (on) switch is turn off(not all but random its happen)



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")

if let _ = cell else
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")

if let d = self.data
cell?.textLabel?.text = d[indexPath.row]
let switchView = UISwitch(frame: .zero)
switchView.setOn(self.isFolderIsAdded(folderName: d[indexPath.row]), animated: true)
switchView.tag = indexPath.row // for detect which row switch Changed
switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
cell?.accessoryView = switchView


return cell!


func isFolderIsAdded(folderName:String) -> Bool
for val in listOfSelectedFolder
if(folderName == val )
return true


return false;


@objc func switchChanged(_ sender : UISwitch!)
if let d = self.data
if(sender.isOn)
self.delegate?.selectedSubFolder(name: d[sender.tag])
else
self.delegate?.deleteFilesFromFolder(folderName: d[sender.tag])












share|improve this question
























  • Add else clock in cellForRowAt indexPath and set switchView.setOff and check what Happens.

    – Nikunj Kumbhani
    Mar 7 at 6:47











  • In IOS 12+ simulator have some issue related UI update, Tabbar tapped, button pressed, switch on/off update etc, I have faced the same issue but in the device it works fine, So check this once in the real device.

    – AtulParmar
    Mar 7 at 7:03













1












1








1


1






I have created a UITableView and adding the switch dynamically into each cell the basis is of requirement . if i select a switch and turn it on and immediately select next switch and turn it on, it's having an issue with the state of the switch its changing and a previously selected switch is getting off, its happening only if i select all the switch fast.



enter image description here



here is the image in this i am adding all the switches dynamically as per the data and if i on the first switch it data will load them in the other table . but if i select all the switch fast fast and turn them on some switch will stuck in to off state only . if i tap on the outside of the table its disappear and if again i load the table that time i can see all selected and previously enable (on) switch is turn off(not all but random its happen)



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")

if let _ = cell else
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")

if let d = self.data
cell?.textLabel?.text = d[indexPath.row]
let switchView = UISwitch(frame: .zero)
switchView.setOn(self.isFolderIsAdded(folderName: d[indexPath.row]), animated: true)
switchView.tag = indexPath.row // for detect which row switch Changed
switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
cell?.accessoryView = switchView


return cell!


func isFolderIsAdded(folderName:String) -> Bool
for val in listOfSelectedFolder
if(folderName == val )
return true


return false;


@objc func switchChanged(_ sender : UISwitch!)
if let d = self.data
if(sender.isOn)
self.delegate?.selectedSubFolder(name: d[sender.tag])
else
self.delegate?.deleteFilesFromFolder(folderName: d[sender.tag])












share|improve this question
















I have created a UITableView and adding the switch dynamically into each cell the basis is of requirement . if i select a switch and turn it on and immediately select next switch and turn it on, it's having an issue with the state of the switch its changing and a previously selected switch is getting off, its happening only if i select all the switch fast.



enter image description here



here is the image in this i am adding all the switches dynamically as per the data and if i on the first switch it data will load them in the other table . but if i select all the switch fast fast and turn them on some switch will stuck in to off state only . if i tap on the outside of the table its disappear and if again i load the table that time i can see all selected and previously enable (on) switch is turn off(not all but random its happen)



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")

if let _ = cell else
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")

if let d = self.data
cell?.textLabel?.text = d[indexPath.row]
let switchView = UISwitch(frame: .zero)
switchView.setOn(self.isFolderIsAdded(folderName: d[indexPath.row]), animated: true)
switchView.tag = indexPath.row // for detect which row switch Changed
switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
cell?.accessoryView = switchView


return cell!


func isFolderIsAdded(folderName:String) -> Bool
for val in listOfSelectedFolder
if(folderName == val )
return true


return false;


@objc func switchChanged(_ sender : UISwitch!)
if let d = self.data
if(sender.isOn)
self.delegate?.selectedSubFolder(name: d[sender.tag])
else
self.delegate?.deleteFilesFromFolder(folderName: d[sender.tag])









ios swift xcode uitableview swift4.2






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 7 at 10:19









Mohmmad S

2,4601523




2,4601523










asked Mar 7 at 6:36









Ankita KhareAnkita Khare

64




64












  • Add else clock in cellForRowAt indexPath and set switchView.setOff and check what Happens.

    – Nikunj Kumbhani
    Mar 7 at 6:47











  • In IOS 12+ simulator have some issue related UI update, Tabbar tapped, button pressed, switch on/off update etc, I have faced the same issue but in the device it works fine, So check this once in the real device.

    – AtulParmar
    Mar 7 at 7:03

















  • Add else clock in cellForRowAt indexPath and set switchView.setOff and check what Happens.

    – Nikunj Kumbhani
    Mar 7 at 6:47











  • In IOS 12+ simulator have some issue related UI update, Tabbar tapped, button pressed, switch on/off update etc, I have faced the same issue but in the device it works fine, So check this once in the real device.

    – AtulParmar
    Mar 7 at 7:03
















Add else clock in cellForRowAt indexPath and set switchView.setOff and check what Happens.

– Nikunj Kumbhani
Mar 7 at 6:47





Add else clock in cellForRowAt indexPath and set switchView.setOff and check what Happens.

– Nikunj Kumbhani
Mar 7 at 6:47













In IOS 12+ simulator have some issue related UI update, Tabbar tapped, button pressed, switch on/off update etc, I have faced the same issue but in the device it works fine, So check this once in the real device.

– AtulParmar
Mar 7 at 7:03





In IOS 12+ simulator have some issue related UI update, Tabbar tapped, button pressed, switch on/off update etc, I have faced the same issue but in the device it works fine, So check this once in the real device.

– AtulParmar
Mar 7 at 7:03












3 Answers
3






active

oldest

votes


















2














This is a reuse problem.
when you scroll the tableView, The cell is then reused.
the switch on it will be reset.



You need follow MVC Design patterns.
use a model to help you.
Like this



class CellModel 
var name = ""
var switchOn = false


var dataSource = [CellModel]()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomCell
cell.model = dataSource[indexPath.row]
return cell

class CustomCell: UITableViewCell

var model: CellModel?
didSet
switchView.isOn = model?.switchOn ?? false


init(xxxx)
switchView.addTarget(self, action:#selector(self.switchChanged(_:)), for: .valueChanged)



@objc func switchChanged(_ sender : UISwitch!)
model.switchOn = sender.isOn







share|improve this answer






























    0














    When Reusing a tableViewCell Always remember to use.



    1- prepareForReuse method in tableViewCell class



    2- write else conditions for all if conditions specially if you are updating any UI in if condition



    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
    var cell = tableView.dequeueReusableCell(withIdentifier: "cell")

    if let _ = cell else
    cell = UITableViewCell(style: .default, reuseIdentifier: "cell")

    if let d = self.data
    cell?.textLabel?.text = d[indexPath.row]
    let switchView = UISwitch(frame: .zero)
    switchView.setOn(self.isFolderIsAdded(folderName: d[indexPath.row]), animated: true)
    switchView.tag = indexPath.row // for detect which row switch Changed
    switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
    cell?.accessoryView = switchView

    else
    // Update your UI if data not found like turn your switch off etc ...

    return cell!



    3- Or It might be an issue of your simulator after update of Xcode 9.0 simulator are now not good as they were till Xcode 8.X






    share|improve this answer






























      0














      I am tried your code with some changes, it is working fine. It is not an issue with tableView.dequeueReusableCell. Please try the code below.



      import UIKit

      class FirstViewController: UIViewController,UITableViewDelegate, UITableViewDataSource



      @IBOutlet weak var tableView: UITableView!
      var listOfSelectedFolder = ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""]
      var listOfSelectedFolder2 = ["sample text 0","sample text 1","sample text 2","sample text 4","sample text 5","sample text 6","sample text 7","sample text 8","sample text 9","sample text 10","sample text 11","sample text 12","sample text 13","sample text 14","sample text 15","sample text 16","sample text 17","sample text 18","sample text 19","sample text 20","sample text 21","sample text 22","sample text 23","sample text 24","sample text 25","sample text 26","sample text 27","sample text 28","sample text 29","sample text 30","sample text 31","sample text 32","sample text 33","sample text 34","sample text 35","sample text 36","sample text 37","sample text 38","sample text 39","sample text 40"]

      override func viewDidLoad()
      super.viewDidLoad()
      self.tableView.delegate = self
      self.tableView.dataSource = self
      // Do any additional setup after loading the view, typically from a nib.



      override func didReceiveMemoryWarning()
      super.didReceiveMemoryWarning()
      // Dispose of any resources that can be recreated.


      /// tableview datasouce methodes

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

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


      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
      var cell = tableView.dequeueReusableCell(withIdentifier: "cell")

      if let _ = cell else
      cell = UITableViewCell(style: .default, reuseIdentifier: "cell")

      let foldername = listOfSelectedFolder2[indexPath.row]
      cell?.textLabel?.text = foldername
      let switchView = UISwitch(frame: .zero)
      switchView.setOn(self.isFolderIsAdded(folderName: foldername), animated: true)
      switchView.tag = indexPath.row // for detect which row switch Changed
      switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
      cell?.accessoryView = switchView

      return cell!

      func isFolderIsAdded(folderName:String) -> Bool

      return listOfSelectedFolder.contains(folderName);


      @objc func switchChanged(_ sender : UISwitch!)
      if(sender.isOn)

      self.listOfSelectedFolder.insert(self.listOfSelectedFolder2[sender.tag], at: sender.tag)
      else
      self.listOfSelectedFolder.remove(at: sender.tag)
      self.listOfSelectedFolder.insert("", at: sender.tag)





      In case you still have the same issue, maybe the UI updates happening on the background thread. So make sure the UI updating code is running on the main thread.



      dispatch_async(dispatch_get_main_queue(), code)


      or



      DispatchQueue.main.async code





      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%2f55037485%2ftableview-dynamic-switches-having-issue-if-i-select-the-switch-and-make-it-on%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        2














        This is a reuse problem.
        when you scroll the tableView, The cell is then reused.
        the switch on it will be reset.



        You need follow MVC Design patterns.
        use a model to help you.
        Like this



        class CellModel 
        var name = ""
        var switchOn = false


        var dataSource = [CellModel]()

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomCell
        cell.model = dataSource[indexPath.row]
        return cell

        class CustomCell: UITableViewCell

        var model: CellModel?
        didSet
        switchView.isOn = model?.switchOn ?? false


        init(xxxx)
        switchView.addTarget(self, action:#selector(self.switchChanged(_:)), for: .valueChanged)



        @objc func switchChanged(_ sender : UISwitch!)
        model.switchOn = sender.isOn







        share|improve this answer



























          2














          This is a reuse problem.
          when you scroll the tableView, The cell is then reused.
          the switch on it will be reset.



          You need follow MVC Design patterns.
          use a model to help you.
          Like this



          class CellModel 
          var name = ""
          var switchOn = false


          var dataSource = [CellModel]()

          func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
          let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomCell
          cell.model = dataSource[indexPath.row]
          return cell

          class CustomCell: UITableViewCell

          var model: CellModel?
          didSet
          switchView.isOn = model?.switchOn ?? false


          init(xxxx)
          switchView.addTarget(self, action:#selector(self.switchChanged(_:)), for: .valueChanged)



          @objc func switchChanged(_ sender : UISwitch!)
          model.switchOn = sender.isOn







          share|improve this answer

























            2












            2








            2







            This is a reuse problem.
            when you scroll the tableView, The cell is then reused.
            the switch on it will be reset.



            You need follow MVC Design patterns.
            use a model to help you.
            Like this



            class CellModel 
            var name = ""
            var switchOn = false


            var dataSource = [CellModel]()

            func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomCell
            cell.model = dataSource[indexPath.row]
            return cell

            class CustomCell: UITableViewCell

            var model: CellModel?
            didSet
            switchView.isOn = model?.switchOn ?? false


            init(xxxx)
            switchView.addTarget(self, action:#selector(self.switchChanged(_:)), for: .valueChanged)



            @objc func switchChanged(_ sender : UISwitch!)
            model.switchOn = sender.isOn







            share|improve this answer













            This is a reuse problem.
            when you scroll the tableView, The cell is then reused.
            the switch on it will be reset.



            You need follow MVC Design patterns.
            use a model to help you.
            Like this



            class CellModel 
            var name = ""
            var switchOn = false


            var dataSource = [CellModel]()

            func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomCell
            cell.model = dataSource[indexPath.row]
            return cell

            class CustomCell: UITableViewCell

            var model: CellModel?
            didSet
            switchView.isOn = model?.switchOn ?? false


            init(xxxx)
            switchView.addTarget(self, action:#selector(self.switchChanged(_:)), for: .valueChanged)



            @objc func switchChanged(_ sender : UISwitch!)
            model.switchOn = sender.isOn








            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 7 at 7:15









            王永吉王永吉

            363




            363























                0














                When Reusing a tableViewCell Always remember to use.



                1- prepareForReuse method in tableViewCell class



                2- write else conditions for all if conditions specially if you are updating any UI in if condition



                func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
                var cell = tableView.dequeueReusableCell(withIdentifier: "cell")

                if let _ = cell else
                cell = UITableViewCell(style: .default, reuseIdentifier: "cell")

                if let d = self.data
                cell?.textLabel?.text = d[indexPath.row]
                let switchView = UISwitch(frame: .zero)
                switchView.setOn(self.isFolderIsAdded(folderName: d[indexPath.row]), animated: true)
                switchView.tag = indexPath.row // for detect which row switch Changed
                switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
                cell?.accessoryView = switchView

                else
                // Update your UI if data not found like turn your switch off etc ...

                return cell!



                3- Or It might be an issue of your simulator after update of Xcode 9.0 simulator are now not good as they were till Xcode 8.X






                share|improve this answer



























                  0














                  When Reusing a tableViewCell Always remember to use.



                  1- prepareForReuse method in tableViewCell class



                  2- write else conditions for all if conditions specially if you are updating any UI in if condition



                  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
                  var cell = tableView.dequeueReusableCell(withIdentifier: "cell")

                  if let _ = cell else
                  cell = UITableViewCell(style: .default, reuseIdentifier: "cell")

                  if let d = self.data
                  cell?.textLabel?.text = d[indexPath.row]
                  let switchView = UISwitch(frame: .zero)
                  switchView.setOn(self.isFolderIsAdded(folderName: d[indexPath.row]), animated: true)
                  switchView.tag = indexPath.row // for detect which row switch Changed
                  switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
                  cell?.accessoryView = switchView

                  else
                  // Update your UI if data not found like turn your switch off etc ...

                  return cell!



                  3- Or It might be an issue of your simulator after update of Xcode 9.0 simulator are now not good as they were till Xcode 8.X






                  share|improve this answer

























                    0












                    0








                    0







                    When Reusing a tableViewCell Always remember to use.



                    1- prepareForReuse method in tableViewCell class



                    2- write else conditions for all if conditions specially if you are updating any UI in if condition



                    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
                    var cell = tableView.dequeueReusableCell(withIdentifier: "cell")

                    if let _ = cell else
                    cell = UITableViewCell(style: .default, reuseIdentifier: "cell")

                    if let d = self.data
                    cell?.textLabel?.text = d[indexPath.row]
                    let switchView = UISwitch(frame: .zero)
                    switchView.setOn(self.isFolderIsAdded(folderName: d[indexPath.row]), animated: true)
                    switchView.tag = indexPath.row // for detect which row switch Changed
                    switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
                    cell?.accessoryView = switchView

                    else
                    // Update your UI if data not found like turn your switch off etc ...

                    return cell!



                    3- Or It might be an issue of your simulator after update of Xcode 9.0 simulator are now not good as they were till Xcode 8.X






                    share|improve this answer













                    When Reusing a tableViewCell Always remember to use.



                    1- prepareForReuse method in tableViewCell class



                    2- write else conditions for all if conditions specially if you are updating any UI in if condition



                    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
                    var cell = tableView.dequeueReusableCell(withIdentifier: "cell")

                    if let _ = cell else
                    cell = UITableViewCell(style: .default, reuseIdentifier: "cell")

                    if let d = self.data
                    cell?.textLabel?.text = d[indexPath.row]
                    let switchView = UISwitch(frame: .zero)
                    switchView.setOn(self.isFolderIsAdded(folderName: d[indexPath.row]), animated: true)
                    switchView.tag = indexPath.row // for detect which row switch Changed
                    switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
                    cell?.accessoryView = switchView

                    else
                    // Update your UI if data not found like turn your switch off etc ...

                    return cell!



                    3- Or It might be an issue of your simulator after update of Xcode 9.0 simulator are now not good as they were till Xcode 8.X







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 7 at 12:21









                    Abu Ul HassanAbu Ul Hassan

                    323319




                    323319





















                        0














                        I am tried your code with some changes, it is working fine. It is not an issue with tableView.dequeueReusableCell. Please try the code below.



                        import UIKit

                        class FirstViewController: UIViewController,UITableViewDelegate, UITableViewDataSource



                        @IBOutlet weak var tableView: UITableView!
                        var listOfSelectedFolder = ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""]
                        var listOfSelectedFolder2 = ["sample text 0","sample text 1","sample text 2","sample text 4","sample text 5","sample text 6","sample text 7","sample text 8","sample text 9","sample text 10","sample text 11","sample text 12","sample text 13","sample text 14","sample text 15","sample text 16","sample text 17","sample text 18","sample text 19","sample text 20","sample text 21","sample text 22","sample text 23","sample text 24","sample text 25","sample text 26","sample text 27","sample text 28","sample text 29","sample text 30","sample text 31","sample text 32","sample text 33","sample text 34","sample text 35","sample text 36","sample text 37","sample text 38","sample text 39","sample text 40"]

                        override func viewDidLoad()
                        super.viewDidLoad()
                        self.tableView.delegate = self
                        self.tableView.dataSource = self
                        // Do any additional setup after loading the view, typically from a nib.



                        override func didReceiveMemoryWarning()
                        super.didReceiveMemoryWarning()
                        // Dispose of any resources that can be recreated.


                        /// tableview datasouce methodes

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

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


                        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
                        var cell = tableView.dequeueReusableCell(withIdentifier: "cell")

                        if let _ = cell else
                        cell = UITableViewCell(style: .default, reuseIdentifier: "cell")

                        let foldername = listOfSelectedFolder2[indexPath.row]
                        cell?.textLabel?.text = foldername
                        let switchView = UISwitch(frame: .zero)
                        switchView.setOn(self.isFolderIsAdded(folderName: foldername), animated: true)
                        switchView.tag = indexPath.row // for detect which row switch Changed
                        switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
                        cell?.accessoryView = switchView

                        return cell!

                        func isFolderIsAdded(folderName:String) -> Bool

                        return listOfSelectedFolder.contains(folderName);


                        @objc func switchChanged(_ sender : UISwitch!)
                        if(sender.isOn)

                        self.listOfSelectedFolder.insert(self.listOfSelectedFolder2[sender.tag], at: sender.tag)
                        else
                        self.listOfSelectedFolder.remove(at: sender.tag)
                        self.listOfSelectedFolder.insert("", at: sender.tag)





                        In case you still have the same issue, maybe the UI updates happening on the background thread. So make sure the UI updating code is running on the main thread.



                        dispatch_async(dispatch_get_main_queue(), code)


                        or



                        DispatchQueue.main.async code





                        share|improve this answer



























                          0














                          I am tried your code with some changes, it is working fine. It is not an issue with tableView.dequeueReusableCell. Please try the code below.



                          import UIKit

                          class FirstViewController: UIViewController,UITableViewDelegate, UITableViewDataSource



                          @IBOutlet weak var tableView: UITableView!
                          var listOfSelectedFolder = ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""]
                          var listOfSelectedFolder2 = ["sample text 0","sample text 1","sample text 2","sample text 4","sample text 5","sample text 6","sample text 7","sample text 8","sample text 9","sample text 10","sample text 11","sample text 12","sample text 13","sample text 14","sample text 15","sample text 16","sample text 17","sample text 18","sample text 19","sample text 20","sample text 21","sample text 22","sample text 23","sample text 24","sample text 25","sample text 26","sample text 27","sample text 28","sample text 29","sample text 30","sample text 31","sample text 32","sample text 33","sample text 34","sample text 35","sample text 36","sample text 37","sample text 38","sample text 39","sample text 40"]

                          override func viewDidLoad()
                          super.viewDidLoad()
                          self.tableView.delegate = self
                          self.tableView.dataSource = self
                          // Do any additional setup after loading the view, typically from a nib.



                          override func didReceiveMemoryWarning()
                          super.didReceiveMemoryWarning()
                          // Dispose of any resources that can be recreated.


                          /// tableview datasouce methodes

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

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


                          func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
                          var cell = tableView.dequeueReusableCell(withIdentifier: "cell")

                          if let _ = cell else
                          cell = UITableViewCell(style: .default, reuseIdentifier: "cell")

                          let foldername = listOfSelectedFolder2[indexPath.row]
                          cell?.textLabel?.text = foldername
                          let switchView = UISwitch(frame: .zero)
                          switchView.setOn(self.isFolderIsAdded(folderName: foldername), animated: true)
                          switchView.tag = indexPath.row // for detect which row switch Changed
                          switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
                          cell?.accessoryView = switchView

                          return cell!

                          func isFolderIsAdded(folderName:String) -> Bool

                          return listOfSelectedFolder.contains(folderName);


                          @objc func switchChanged(_ sender : UISwitch!)
                          if(sender.isOn)

                          self.listOfSelectedFolder.insert(self.listOfSelectedFolder2[sender.tag], at: sender.tag)
                          else
                          self.listOfSelectedFolder.remove(at: sender.tag)
                          self.listOfSelectedFolder.insert("", at: sender.tag)





                          In case you still have the same issue, maybe the UI updates happening on the background thread. So make sure the UI updating code is running on the main thread.



                          dispatch_async(dispatch_get_main_queue(), code)


                          or



                          DispatchQueue.main.async code





                          share|improve this answer

























                            0












                            0








                            0







                            I am tried your code with some changes, it is working fine. It is not an issue with tableView.dequeueReusableCell. Please try the code below.



                            import UIKit

                            class FirstViewController: UIViewController,UITableViewDelegate, UITableViewDataSource



                            @IBOutlet weak var tableView: UITableView!
                            var listOfSelectedFolder = ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""]
                            var listOfSelectedFolder2 = ["sample text 0","sample text 1","sample text 2","sample text 4","sample text 5","sample text 6","sample text 7","sample text 8","sample text 9","sample text 10","sample text 11","sample text 12","sample text 13","sample text 14","sample text 15","sample text 16","sample text 17","sample text 18","sample text 19","sample text 20","sample text 21","sample text 22","sample text 23","sample text 24","sample text 25","sample text 26","sample text 27","sample text 28","sample text 29","sample text 30","sample text 31","sample text 32","sample text 33","sample text 34","sample text 35","sample text 36","sample text 37","sample text 38","sample text 39","sample text 40"]

                            override func viewDidLoad()
                            super.viewDidLoad()
                            self.tableView.delegate = self
                            self.tableView.dataSource = self
                            // Do any additional setup after loading the view, typically from a nib.



                            override func didReceiveMemoryWarning()
                            super.didReceiveMemoryWarning()
                            // Dispose of any resources that can be recreated.


                            /// tableview datasouce methodes

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

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


                            func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
                            var cell = tableView.dequeueReusableCell(withIdentifier: "cell")

                            if let _ = cell else
                            cell = UITableViewCell(style: .default, reuseIdentifier: "cell")

                            let foldername = listOfSelectedFolder2[indexPath.row]
                            cell?.textLabel?.text = foldername
                            let switchView = UISwitch(frame: .zero)
                            switchView.setOn(self.isFolderIsAdded(folderName: foldername), animated: true)
                            switchView.tag = indexPath.row // for detect which row switch Changed
                            switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
                            cell?.accessoryView = switchView

                            return cell!

                            func isFolderIsAdded(folderName:String) -> Bool

                            return listOfSelectedFolder.contains(folderName);


                            @objc func switchChanged(_ sender : UISwitch!)
                            if(sender.isOn)

                            self.listOfSelectedFolder.insert(self.listOfSelectedFolder2[sender.tag], at: sender.tag)
                            else
                            self.listOfSelectedFolder.remove(at: sender.tag)
                            self.listOfSelectedFolder.insert("", at: sender.tag)





                            In case you still have the same issue, maybe the UI updates happening on the background thread. So make sure the UI updating code is running on the main thread.



                            dispatch_async(dispatch_get_main_queue(), code)


                            or



                            DispatchQueue.main.async code





                            share|improve this answer













                            I am tried your code with some changes, it is working fine. It is not an issue with tableView.dequeueReusableCell. Please try the code below.



                            import UIKit

                            class FirstViewController: UIViewController,UITableViewDelegate, UITableViewDataSource



                            @IBOutlet weak var tableView: UITableView!
                            var listOfSelectedFolder = ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""]
                            var listOfSelectedFolder2 = ["sample text 0","sample text 1","sample text 2","sample text 4","sample text 5","sample text 6","sample text 7","sample text 8","sample text 9","sample text 10","sample text 11","sample text 12","sample text 13","sample text 14","sample text 15","sample text 16","sample text 17","sample text 18","sample text 19","sample text 20","sample text 21","sample text 22","sample text 23","sample text 24","sample text 25","sample text 26","sample text 27","sample text 28","sample text 29","sample text 30","sample text 31","sample text 32","sample text 33","sample text 34","sample text 35","sample text 36","sample text 37","sample text 38","sample text 39","sample text 40"]

                            override func viewDidLoad()
                            super.viewDidLoad()
                            self.tableView.delegate = self
                            self.tableView.dataSource = self
                            // Do any additional setup after loading the view, typically from a nib.



                            override func didReceiveMemoryWarning()
                            super.didReceiveMemoryWarning()
                            // Dispose of any resources that can be recreated.


                            /// tableview datasouce methodes

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

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


                            func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
                            var cell = tableView.dequeueReusableCell(withIdentifier: "cell")

                            if let _ = cell else
                            cell = UITableViewCell(style: .default, reuseIdentifier: "cell")

                            let foldername = listOfSelectedFolder2[indexPath.row]
                            cell?.textLabel?.text = foldername
                            let switchView = UISwitch(frame: .zero)
                            switchView.setOn(self.isFolderIsAdded(folderName: foldername), animated: true)
                            switchView.tag = indexPath.row // for detect which row switch Changed
                            switchView.addTarget(self, action: #selector(self.switchChanged(_:)), for: .valueChanged)
                            cell?.accessoryView = switchView

                            return cell!

                            func isFolderIsAdded(folderName:String) -> Bool

                            return listOfSelectedFolder.contains(folderName);


                            @objc func switchChanged(_ sender : UISwitch!)
                            if(sender.isOn)

                            self.listOfSelectedFolder.insert(self.listOfSelectedFolder2[sender.tag], at: sender.tag)
                            else
                            self.listOfSelectedFolder.remove(at: sender.tag)
                            self.listOfSelectedFolder.insert("", at: sender.tag)





                            In case you still have the same issue, maybe the UI updates happening on the background thread. So make sure the UI updating code is running on the main thread.



                            dispatch_async(dispatch_get_main_queue(), code)


                            or



                            DispatchQueue.main.async code






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 7 at 15:04









                            JosephJoseph

                            4411




                            4411



























                                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%2f55037485%2ftableview-dynamic-switches-having-issue-if-i-select-the-switch-and-make-it-on%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

                                Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                                Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                                Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved