ios - 用户界面搜索栏不显示结果,直到没有点击取消按钮

标签 ios iphone swift xcode uisearchbar

我正在尝试实现搜索功能。它将接受用户的输入,并在按下搜索按钮时返回结果。 我有搜索 This example .

但是这个例子对我没有用。我有一个这样的 cade。

override func viewDidLoad() {
    super.viewDidLoad()
    // Setup the Location Search bar Controller
    let locationSearchTable = storyboard!.instantiateViewController(withIdentifier: "SearchViewController") as! SearchViewController
    resultSearchController = UISearchController(searchResultsController: locationSearchTable)
    resultSearchController?.searchResultsUpdater = locationSearchTable

    searchBar = resultSearchController!.searchBar
    searchBar.sizeToFit()
    searchBar.placeholder = "Search"
    searchBar.delegate = self
    navigationItem.titleView = resultSearchController?.searchBar

    resultSearchController?.hidesNavigationBarDuringPresentation = false
    resultSearchController?.dimsBackgroundDuringPresentation = true

    definesPresentationContext = true
}

Another Function is

extension SearchViewController : UISearchResultsUpdating, UISearchBarDelegate {
func updateSearchResults(for searchController: UISearchController) {
    self.view.isHidden = false
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    self.viewList.removeAll()
    getListOfItem(searchBar.text!)
 }
}

And my getListOfItem taking data from data base and after receiving data i am reloading my UITableView from that function.

func getListOfItem(_ query : String){
    if !loadingData {
        self.viewList.removeAll()
    }
    let request = NSMutableURLRequest(url: URL(string: MyUrl.API_SERVER_URL)!)
    request.httpMethod = "POST"
    let postString = "tag=search&p=\(query)&page=\(String(pageNo))"
    print("postString=\(postString)")
    DispatchQueue.main.async {
        self.startSpinner()
    }
    request.httpBody = postString.data(using: String.Encoding.utf8)
    let task = URLSession.shared.dataTask(with: request as URLRequest) {
        data, response, error in
        if(error != nil){
            self.loadingData = false
            DispatchQueue.main.async {
                self.stopSpinner()
            }
            let nsError = error! as NSError
            let dialog = UIAlertController(title: "Internal Server Error?", message: nsError.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
            dialog.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))

            DispatchQueue.main.async(execute: {
                self.present(dialog, animated: true, completion: nil)
            })

        } else{
            self.loadingData = false
            do {
                var success : Int = 0
                let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String : AnyObject]
                success = jsonObj["success"]! as! Int
                if success == 1 {
                    let json = jsonObj["data"]as? NSArray
                    self.pageNo = self.pageNo + 1
                    DispatchQueue.main.async {
                        for i in 0 ..< json!.count {
                            let productObj  = json![i]as? [String: AnyObject]
                            let newModel = Search()
                            newModel.attributeId =  productObj!["AttributeID"] as? String
                            newModel.attributePrice = productObj!["AttributePrice"] as? String
                            newModel.imageURL = productObj!["ImageURL"] as? String
                            newModel.inventoryCurrent = productObj!["InventoryCurrent"] as? String
                            newModel.pageText = productObj!["PageText"] as? String
                            newModel.productDescription = productObj!["ProductDescription"] as? String
                            newModel.pageURL = productObj!["PageURL"] as? String
                            newModel.productID = productObj!["ProductID"] as? String
                            newModel.productName = productObj!["ProductName"] as? String
                            newModel.thumbURL = productObj!["ThumbURL"] as? String
                            newModel.internationalShipping = productObj!["internationalShipping"] as? String
                            newModel.maxQty = productObj!["maxQty"] as? String
                            newModel.productDisplay = productObj!["productDisplay"] as? String
                            self.viewList.append(newModel)

                        }

                    }
                }
                DispatchQueue.main.async {
                    print("reload")
                    self.checkItems()
                    self.viewListTable.reloadData()
                    //self.view.layoutIfNeeded()
                }
            } catch {
            }
            DispatchQueue.main.async(execute: {
                self.stopSpinner()
            })
        }
    }
    task.resume();
}

This function is getting data from data base and also reloading myTableView. Result is not showing until i clicked on cancel button of UISearchBar. Please help me for that thanks.

UPDATED I have just resolve that issue after adding some code in searchBarSearchButtonClicked() i have add self.resultSearchController?.view.isHidden = true this line but here i can not scroll my table directly. Means i can scroll my table after on tap on that

最佳答案

After Adding some line of code in my searchBarSearchButtonClicked. My problem is getting resolved.

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    self.viewList.removeAll()
    self.searchBar.resignFirstResponder()//This Line Remove the keyboard
    self.resultSearchController?.view.isHidden = true // This line Hide current View
    self.viewListTable.reloadData()
    pageNo = 1
    self.searchStr = searchBar.text! // This Line taking a search string into global variable for future use.
    self.resultSearchController?.isActive = false // This Line for inActivate searchView.
    getListOfItem()
}

Before using Make Sure the hierarchy of all line which is written in that function.

关于ios - 用户界面搜索栏不显示结果,直到没有点击取消按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44718469/

相关文章:

ios - 发送http删除请求

objective-c - UITableViewCell accessoryType位置随单元格高度变化

macos - 沙盒应用程序自动启动,无需 ServiceManagement

objective-c - 刷新 UIViewController 的界面方向

ios - 如何混入 Objective-C 方法的完成 block ?

ios - APNS 从多个服务器发送通知

ios - 缓存 View Controller

iOS - 在 UITextView 中突出显示一个词或多个词

ios - 衡量强/弱ARC引用的影响-对执行时间的影响

ios - 将具有多个 subview 的 View 截图为 wkwebview