UISearchController issue, NSLayoutAttribute do not work in real device

社会主义新天地 提交于 2019-12-13 12:44:46

问题


When click the searchController's cancel button, the Searchbar send back too much, I use constraint to solve that, but ,NSLayoutAttibute do not work on real device, but only work on sumilator, using UISearchController in my project , there is a strange issue:

So I think out a method to solve the issue, in the UISearchBarDelegate delegate method, when cancel(取消) button click, set the top constant to 0:

// MARK: - search delegate
func searchBarCancelButtonClicked() {

    for item:NSLayoutConstraint in self.tableView.constraints {

        self.view.setNeedsLayout()
        if item.firstAttribute == NSLayoutAttribute.top {
            item.constant = 0
        }
    }
}

It is real work for simulator, but it not work on real device, :(

1) On the simulator, works fine:

2) On the real device (I have tested in 5c and 6, 6p), the issue still exist.


The code

I think something maybe useful, so I post the code below:

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]?

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()  {

    // 1.配置
    self.resultSearchController = UISearchController(searchResultsController: nil)
    self.resultSearchController.searchResultsUpdater = self
    self.resultSearchController.dimsBackgroundDuringPresentation = false
    self.resultSearchController.searchBar.sizeToFit()
    self.resultSearchController.searchBar.placeholder = "搜索"
    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!)

        // 2.隐藏cell下的Line
        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("取消", forKey:"_cancelButtonText")
    }

    // 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.鹿鸣提示标题, detail_Title: "请选择门店!", cancleButtonTitle: "取消", confirmButtonTitle: "确定", action: { (button) in

            })

            return
        }

        _ = 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_bussiness 后台写错了
                //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()  // 刷新tableView

            }else if stateCode == -1 {

                // 弹窗系统错误
                SVProgressHUD.showError(withStatus: "系统错误")

            }

        }, failBlcok: {

            // 弹窗系统错误
            SVProgressHUD.showError(withStatus: "系统错误")
        })

    }

    // 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

        // 配置cell
        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()
    }


}

How to deal with the strange issue?

来源:https://stackoverflow.com/questions/40974647/uisearchcontroller-issue-nslayoutattribute-do-not-work-in-real-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!