Search code examples
swiftviewuikittableview

Change data in tableView swift


I am working on a project to change the array that is being displayed by a tableview when the segment value is changed. What is the easiest way to accomplish this? Thanks!

  @IBAction func segmentValueChanged(_ sender: UISegmentedControl) {
        if sender == testSwitcher {
            if testSwitcher.selectedSegmentIndex == 0 {
                print("Hello World")
            }
            else if testSwitcher.selectedSegmentIndex == 1 {
                print("Data Update")
                newArray = []
                stateElections.data = newArray
                stateElections.reloadData()
     }

Solution

  • You can implement something like below

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
        {
            let myCell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath)
            
            switch(mySegmentedControl.selectedSegmentIndex)
            {
            case 0:
                myCell.textLabel!.text = arrayList1[indexPath.row]
                break
            case 1:
                myCell.textLabel!.text = arrayList2[indexPath.row]
                break
                
            case 2:
                myCell.textLabel!.text = arrayList3[indexPath.row]
                break
                
            default:
                break
                
            }
    
    
            return myCell
        }
        
        
        @IBAction func segmentedControlActionChanged(sender: AnyObject) {
        
            myTableView.reloadData()
        }