Search code examples
iosswiftuitableviewuisegmentedcontrol

UITableView Not Changing on segmentedControlChanged


I'm using Realm to load data into my UITableView and I've set a UISegmentedControl as the title in my navigation; but when segmentedControlChanged is triggered, nothing in my tableView changes.

var productViewSegmentedControl: UISegmentedControl? = nil
let realm = try! Realm()
var allProducts : Results<Product>?

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if allProducts == nil {
        allProducts = realm.objects(Product.self).sorted(byKeyPath: "basedescription")
    }

    if productViewSegmentedControl == nil {
        let segmentedControlItems = ["List", "Brands", "Categories"]
        productViewSegmentedControl = UISegmentedControl(items: segmentedControlItems)
        productViewSegmentedControl?.selectedSegmentIndex = 0

        self.navigationItem.titleView = productViewSegmentedControl
        productViewSegmentedControl?.addTarget(self, action: #selector(OrderFormViewController.segmentedControlChanged(_:)), for:.allEvents)
    }

}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

}

func segmentedControlChanged(_ segControl: UISegmentedControl){

    switch segControl.selectedSegmentIndex{
        case 0:
            _ = allProducts?.sorted(byKeyPath: "basedescription")
            tableView.reloadData()

        case 1:
            _ = allProducts?.sorted(byKeyPath: "itembrand")
            tableView.reloadData()

        case 2:
            _ = allProducts?.sorted(byKeyPath: "itemtype")
            tableView.reloadData()

        default: break

    }
}

Solution

  • Why do you do:

    _ = allProducts?.sorted(byKeyPath: "basedescription")
    

    You are ignoring the result so nothing changes. The sorted method does not update the sender, it returns a new collection.

    You need to update allProducts so the table view changes when you reload it.

    You probably want (if this is supported by Realm):

    allProducts?.sort(byKeyPath: "basedescription")
    

    or:

    allProducts = allProducts?.sorted(byKeyPath: "basedescription")
    

    And of course you need to update the other cases as well.