ios - 搜索栏在 IOS 应用程序 swift 3 中不起作用

标签 ios swift

我想在我的 swift 应用程序中实现一个搜索栏,我已经成功地做到了,但是由于某种原因,当我去搜索任何东西时,我的 TableView 中没有显示任何帮助,我们将不胜感激。

这是我的 Controller

import UIKit
import AudioToolbox


class TableController: UITableViewController, UISearchBarDelegate{


    var PhoneArray = [String]()

    var filtered:[String] = []

    var searchActive = false



    @IBOutlet weak var searchBar: UISearchBar!




    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self
        searchBar.delegate = self
        searchBar.returnKeyType = UIReturnKeyType.done
        getData("http://phonedir.mydomain.com/getPhoneList")
    }


    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if(searchActive)
        {
          print("Search")
          return filtered.count

        }
        return PhoneArray.count
    }


    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

        if searchBar.text == nil || searchBar.text == "" {

            searchActive = false
            print("search not active")
            view.endEditing(true)

            tableView.reloadData()

        } else {

            searchActive = true
            print("search is active")
            filtered = PhoneArray.filter({$0 == searchBar.text})

            tableView.reloadData()
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        //let phone = PhoneData[indexPath.row]
        //let name = indexPath.row
        if(searchActive)
        {
            let array = filtered[indexPath.row]
            //print("search Active")
            cell.textLabel?.text = array.replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "[", with: " ").replacingOccurrences(of: "]", with: " ").replacingOccurrences(of: "&", with: "*")
            cell.textLabel?.numberOfLines=0
            cell.textLabel?.sizeToFit()

            cell.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping

            cell.textLabel?.textColor = UIColor.white

            if (indexPath.row % 2 == 0)
            {
                cell.backgroundColor = UIColor(red: 22/255, green: 160/255, blue: 133/255, alpha: 1.0)
            }
            else
            {
                cell.backgroundColor = UIColor(red: 44/255, green: 62/255, blue: 80/255, alpha: 1.0)
            }
        }
        else
        {
            let array = PhoneArray[indexPath.row]
            //print("search  not Active")

            cell.textLabel?.text = array.replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "[", with: " ").replacingOccurrences(of: "]", with: " ").replacingOccurrences(of: "&", with: "*")
            cell.textLabel?.numberOfLines=0
            cell.textLabel?.sizeToFit()

            cell.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping

            cell.textLabel?.textColor = UIColor.white

            if (indexPath.row % 2 == 0)
            {
                cell.backgroundColor = UIColor(red: 22/255, green: 160/255, blue: 133/255, alpha: 1.0)
            }
            else
            {
                cell.backgroundColor = UIColor(red: 44/255, green: 62/255, blue: 80/255, alpha: 1.0)
            }
        }

        return cell
    }



    func getData(_ link:String)
    {
        let url = URL(string: link)!
        let request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 20)
        URLSession.shared.dataTask(with: request) { (data, response, error) in
            if error != nil {
                print(error!)
                let alertController = UIAlertController(title: "No Connection", message:
                    "Phone directory connection could not be established", preferredStyle: UIAlertControllerStyle.alert)
                alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))

                self.present(alertController, animated: true, completion: nil)

                return
            }

            do {
                if let jsonData = try JSONSerialization.jsonObject(with:data!, options: []) as? [[String:Any]] {
                    //print(jsonData)
                    for item in jsonData {

                        if let phone_first = item["EMP_FIRST_NAME"] as? String
                        {
                            if let phone_last = item["EMP_LAST_NAME"] as? String
                            {
                                if let phone_ext = item["PHONE_EXT"] as? String
                                {



                                    self.PhoneArray.append(" [" + phone_first + "]" + " [" + phone_last + "]" + "&" + phone_ext + "&")
                                }
                            }
                        }

                        DispatchQueue.main.async {
                            self.tableView.reloadData()
                        }
                    }
                }
            } catch let error as NSError {
                print(error)
            }
            }.resume()

            //print(self.PhoneArray)
    }

}

这是我在没有搜索的情况下正常加载时的样子

Without Search

这是我进行搜索时的样子,如您所见,我的表格 View 没有显示任何内容

With Search

最佳答案

问题出在这里:

filtered = PhoneArray.filter({$0 == searchBar.text})

您应该检查字符串是否包含搜索文本

filtered = PhoneArray.filter({$0.contains(searchBar.text)})

关于ios - 搜索栏在 IOS 应用程序 swift 3 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46364846/

相关文章:

ios - Xcode GUI 与编程枚举中 UIPageViewController.transitionStyle 的不同选项

swift - 一次多次调用 DispatchSemaphore 的 wait() 是否安全?

Xcode 应用程序中的 iOS 界面过大

ios - 如何在 Game Center 多人游戏中获取玩家名称?

iphone - UITableView 在 Forground 状态下 Enter 后不重新加载数据

ios - 当我尝试删除 UITableView 部分时 EXC_BAD_ACCESS

ios - swift 3 : Compiler does not recognize type of subclassed UIView

iphone - 如何增加 NSString 类型变量的保留计数?

ios - 将用户文本字段输入附加到其他 View Controller 中的数组中

ios - 谷歌地图标记 Action