Search code examples
iosuisearchcontroller

SearchController issue, when search the displayController shows a spacing from the Searchbar


The issue is this:

In the storyboard, I must uncheck the Adjust Scroll View Insets, because if not do this, I will get a other issue(https://stackoverflow.com/questions/40974647/uisearchcontroller-issue-nslayoutattribute-do-not-work-in-real-device), and I don't know this if is affect the issue here.(I test in simulator, if check Adjust Scroll View Insets, the issue here will not appear )


My code

import UIKit
import SVProgressHUD

class ChooseStoreViewController: UIViewController,UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating {

    @IBOutlet weak var tableView: UITableView!

    var ori_dataSource: [StoreListModel] = [StoreListModel]()
    var dataSource = [String]()
    var filterdDataSource = [String]()
    var resultSearchController = UISearchController()
    var choosedStore:StoreListModel? = nil

    var userInfoFromChooseTerant:[String:Any]?

    @IBOutlet weak var top_constraint: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()
    
        initData()
        initUI()
    }


    // MARK: - view life
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    
        self.navigationController?.isNavigationBarHidden = false

    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    
        self.navigationController?.isNavigationBarHidden = true
    }

    func initData()  {
    
        self.resultSearchController = UISearchController(searchResultsController: nil)
        self.resultSearchController.searchResultsUpdater = self
        self.resultSearchController.dimsBackgroundDuringPresentation = false
        self.resultSearchController.searchBar.sizeToFit()
        self.resultSearchController.searchBar.placeholder = "search"
        self.resultSearchController.searchBar.tintColor = UIColor.black
        self.resultSearchController.searchBar.delegate = self
        self.tableView.tableHeaderView = self.resultSearchController.searchBar
    
        let nib = UINib(nibName: "TerantListCell", bundle: nil)
        // Required if our subclasses are to use: dequeueReusableCellWithIdentifier:forIndexPath:
        //tableView.register(nib, forCellReuseIdentifier: "TerantListCell")
        self.tableView.register(nib, forCellReuseIdentifier: "TerantListCell")
        self.tableView.tableFooterView = UIView.init()
    
        self.tableView.reloadData()
    
        networkForStoreList()
    }
    func initUI() {
    
        let backNavItem:UIBarButtonItem = UtilSwift.addBackButtonItem(nil, controlelr: self)
        backNavItem.action = #selector(navBack)
    
        // print(userInfoFromChooseTerant!)
    
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
    
    
    }

    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    
        let chooseRole: ChooseRoleViewController = segue.destination as! ChooseRoleViewController
    
        chooseRole.userInfoFromChooseStore = self.userInfoFromChooseTerant
    
    }

    // MARK: - search delegate
    func searchBarCancelButtonClicked() {
     
        for item:NSLayoutConstraint in self.tableView.constraints {
        
            self.view.setNeedsLayout()
            if item.firstAttribute == NSLayoutAttribute.top {
                item.constant = 0
            }
        }
    }

    // MARK: - searchbar delegate
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    

        searchBar.setValue("cancel", forKey:"_cancelButtonText")
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    

    }

    // MARK: - private methods

    func navBack()  {
        _ = self.navigationController?.popViewController(animated: true)
    }

    // MARK: - actions

    @IBAction func unwindToChooseStoreVCFromChooseRole(segue: UIStoryboardSegue){

    
    }

    @IBAction func nextStepAction(_ sender: UIButton) {
    
    /*if choosedStore == nil {
        
        let lml_alert: LMLDropdownAlertView = LMLDropdownAlertView.init(frame: self.view.bounds)
        lml_alert.showAlert(title: Global.hint, detail_Title: "select", cancleButtonTitle: "cacnel", confirmButtonTitle: "confirm", action: { (button) in
            
        })
        
        return
    }*/
    
        self.resultSearchController.isActive = false 
     
        if self.choosedStore != nil {
        
            _ = self.userInfoFromChooseTerant?.updateValue(self.choosedStore!.userId, forKey: "store_id")
        }
    
        self.performSegue(withIdentifier: "ChooseStoreVCToChooseRoleVC", sender: self)
    
    }
 

    // MARK: - network

    func networkForStoreList() {
    
        let params:[String:String] = [
            "createTime":"-1",
            "userId" : self.userInfoFromChooseTerant!["affiliated_id"] as! String
    ]
    
    
        // url_terantList
        Mysevers.afpost(withHud: true, andAddressname: Global.url_listStore, parmas: params, requestSuccess: { (result) in
        
            let stateCode = UtilSwift.getNetStateCode(result: result as Any, key: Global.net_key_stateCode)
        
            if stateCode == 0 {
            
                let storeArr:[[String : Any]] = UtilSwift.getNetAnyObject(result: result as Any, key: "list") as! [[String : Any]]  // Global.net_key_bussines
                //self.ori_dataSource = terantArr
                for item:[String: Any] in storeArr {
                
                    let store_list_model: StoreListModel = StoreListModel.initStoreListModelWithDic(dic: item)
                    self.ori_dataSource.append(store_list_model)
                }
            
            
                for item:StoreListModel in self.ori_dataSource {
                
                    self.dataSource.append(item.name)
                }
            
            
            
                self.tableView.reloadData()  
            
            }else if stateCode == -1 {
            
                SVProgressHUD.showError(withStatus: "err")
            
            }
        
        }, failBlcok: {
        
            SVProgressHUD.showError(withStatus: "err")
        })

    }

    // MARK: - tableView
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
        if self.resultSearchController.isActive {
        
            return filterdDataSource.count
        }else {
        
            return dataSource.count
       }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let cell: TerantListCell = tableView.dequeueReusableCell(withIdentifier: "TerantListCell", for: indexPath) as! TerantListCell
    
        if self.resultSearchController.isActive {
        
            cell.title_label.text = self.filterdDataSource[indexPath.row]
        }else {
        
            cell.title_label?.text = self.dataSource[indexPath.row]
        }
    
        return cell
    
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
        self.choosedStore = self.ori_dataSource[indexPath.row]
    
    }

    // MARK: - regexp

    func updateSearchResults(for searchController: UISearchController) {
    
        self.filterdDataSource.removeAll(keepingCapacity: false)
    
        let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
    
        let array = (self.dataSource as NSArray).filtered(using: searchPredicate)
    
        self.filterdDataSource = array as! [String]
    
        self.tableView.reloadData()
    }


}

Solution

  • Go to ".storyboard" file where "ChooseStoreViewController" exist. Then click on UITableView and change tableView constraints as follows:

    enter image description here

    Check Top Space constraint.