1

I have a vc with one segmentedControl, I want to be able to change the function called by the refresher everytime the segmentedControl's index is changed

lazy var refresher: UIRefreshControl = {
    let refreshControl = UIRefreshControl()
    if (segmentedControl.selectedSegmentIndex == 0){
        refreshControl.addTarget(self, action: #selector(loadRecommend1), for: .valueChanged)
    } else if (segmentedControl.selectedSegmentIndex == 1){
        refreshControl.addTarget(self, action: #selector(loadCompletePosts1), for: .valueChanged)
    } else if (segmentedControl.selectedSegmentIndex == 2){
        refreshControl.addTarget(self, action: #selector(loadCompletePostsByHealthy1), for: .valueChanged)
    }
    return refreshControl
}()

Currently the first function is called everytime despite the selected item in the segmentedControl

Arman Khan
  • 49
  • 1
  • 11

1 Answers1

1

This lazy var is called only once upon creation of this instance not when change of segment index , so you either change that target selector inside a 1 selector method or have only 1 selector that you execute methods according to current segment index like

refreshControl.addTarget(self, action: #selector(allCalls), for: .valueChanged)

@objc func allCalls(_ sender:UIRefreshControl) {
   if (segmentedControl.selectedSegmentIndex == 0){
        loadRecommend1()
   } else if (segmentedControl.selectedSegmentIndex == 1){
        loadCompletePosts1() 
   } else if (segmentedControl.selectedSegmentIndex == 2){
        loadCompletePostsByHealthy1() 
   }
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87