2017-04-04 76 views
1

我使用Realm將數據加載到我的UITableView中,並且我在導航中設置了一個UISegmentedControl作爲標題;但是當segmentedControlChanged被觸發時,我的tableView中沒有任何更改。UITableView不會改變segmentedControlChanged

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 

    } 
} 

回答

2

你爲什麼這樣做:

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

你忽略了這樣的結果沒有什麼變化。 sorted方法不更新發件人,它返回一個新的收藏。

您需要更新allProducts,以便在重新載入表格視圖時更改。

你可能想(如果這是由境界支持):

allProducts?.sort(byKeyPath: "basedescription") 

或:

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

當然,你需要更新的其他案件。

+0

出於某種原因,我認爲使用下劃線更新結果。我會嘗試這種方式。 – Sicypher

+0

不,使用下劃線是爲了在編譯器抱怨你忽略函數調用的返回值時使編譯器安靜。 – rmaddy