MightyAlienDwarf MightyAlienDwarf -4 years ago 257
iOS Question

Swift 3 - Disable & enable segmented control

I've got two table views and I switch between them by selecting a segmented control. I also got a search controller with a search bar. When I select the search bar, the segmented control should be disabled, so that you can't select the second table view. When I click on the cancel button in the search bar, the segmented control should be activated again. But this doesn't work, the segmented control stays disabled.
When I select a table view cell and return to this view controller, then the segmented control is enabled again. But I want it to be enabled when I press the cancel button.
My code looks as follows:

func deactivateSegment() {
segmentedController.setEnabled(false, forSegmentAt: 1)
}

func activateSegment() {
segmentedController.setEnabled(true, forSegmentAt: 1)
}


extension SegmentedTableController: UISearchResultsUpdating, UISearchBarDelegate {

func updateSearchResults(for searchController: UISearchController) {
deactivateSegment()
if searchController.searchBar.text != "" {
filterContentForSearchText(searchText: searchController.searchBar.text!)
} else {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "update_view"), object: rumList, userInfo: nil)
}
}

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
KCFABManager.defaultInstance().hide()
deactivateSegment()
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
KCFABManager.defaultInstance().show()
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "update_view"), object: self.rumList, userInfo: nil)

activateSegment()
}
}


I also tried it with
segmentedController.isEnabled = false (&true)

and
segmentedController.isUserInteractionEnabled = false (&true)

but that also doesn't work.

What am I doing wrong?

Answer Source

remove the deactivateSegment() in the delegate method of updateSearchResults

func updateSearchResults(for searchController: UISearchController) {
   // deactivateSegment()
  if searchController.searchBar.text != "" {

else do like

  func updateSearchResults(for searchController: UISearchController) {

    if searchController.searchBar.text != "" {
        filterContentForSearchText(searchText: searchController.searchBar.text!)
        activateSegment()
    } else {
        deactivateSegment()
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "update_view"), object: rumList, userInfo: nil)
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download