数组中字符串的 UISearchBar

Posted

技术标签:

【中文标题】数组中字符串的 UISearchBar【英文标题】:UISearchBar of an string within an array 【发布时间】:2017-10-20 18:10:02 【问题描述】:

我正在尝试创建一个带有部分标题、标题文本和副标题文本的字典类型的应用程序。我设法使用以下代码使一切正常工作。我唯一想不通的是如何过滤 UISearchBar 以显示数组中字符串 [Coptic] 的结果。这甚至可能是我组织一切的方式还是我需要重组?有人有什么建议吗?

我将 updateSearchResults 的代码留在底部空白,因为我不知道要编写什么代码。

 class Gamma: UITableViewController, UISearchBarDelegate, UISearchResultsUpdating 


    struct words 

        var sectionName : String!
        var coptic : [String]!
        var english : [String]!
    

    var array = [words]()
    var filtered = [words]()
    var filtered2 = UITableViewController()

    var indexarray = ["Ga", "Ge", "Gy", "Gn", "Go", "Gr", "Gw"]

    let searchController = UISearchController(searchResultsController: nil)




    override func viewDidLoad() 
        super.viewDidLoad()


        let defaultTextAttribs = [NSAttributedStringKey.font.rawValue: UIFont(name:"CS Avva Shenouda", size:17), NSAttributedStringKey.foregroundColor.rawValue:UIColor.black]


        UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = defaultTextAttribs as Any as! [String : Any]


        self.navigationController?.navigationBar.tintColor = UIColor.white

        filtered = array

        searchController.searchResultsUpdater = self
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.dimsBackgroundDuringPresentation = false


        self.navigationItem.titleView = searchController.searchBar

        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 400
        tableView.sectionHeaderHeight = 40
        tableView.sectionIndexBackgroundColor = UIColor.clear
        tableView.sectionIndexMinimumDisplayRowCount = 15


        array = [words(sectionName: "Ga", coptic: ["Gabriyl", "gaza", "gazovulakion", "gala", "galynyc", "Galile`a", "galileoc", "gamoc", "gar"], english: ["ghabriyēl\n\n(Heb.) - Gabriel", "ghå`zå\n\n(f.) - Treasure, money chest", "ghåzo`filåk`yon\n\n(Gk.) - Treasury", "ghå`lå\n\n(Gk. m.) - Milk", "ghålēnēs\n\n(Gk. f.) - Gentle, calm", "ghålilā`å\n\nGalilee", "ghålilā`os\n\n(adj.) - Galilean", "ghåmos / gåmos\n\n(Gk. m.) - Wedding, marriage", "ghår\n\n(Gk. conj.) - For, because"]),
        words(sectionName: "Ge", coptic: ["geenna", "gene`a", "genecic", "genneoc", "gennyma", "gennycic", "gennytyc", "gennytria", "genoc", "Gewrgioc"], english: ["ge`ā`nå\n\n(Heb.) - Gehenna, Hades", "gene`å\n\n1. (Gk. f.) - Generation\n\n2. (Gk. f.) - New, recent", "genesis\n\n(Gk. f.) - Birth, start, inception", "gennā`os\n\n(Gk. adj.) - Brave, noble, honorable, good", "gennē`må\n\n(Gk. m.) - Offspring, product", "gennē`sis\n\n(Gk. f.) - Birth, generation", "gennē`tēs\n\n(Gk. m.) - Parent, generator", "gennēt`riyā\n\n(Gk. f.) - Parent, generator", "gā`nos\n\n(Gk. m.) - Race, tribe", "ge`ōrgi`yos\n\nGeorge"]),
                 words(sectionName: "Gy", coptic: ["gy"], english: ["gē\n\n(Gk. f.) - Earth, ground, land"]),
                 words(sectionName: "Gn", coptic: ["gnovoc", "gnwmy", "gnwcic"], english: ["ghno`fos\n\n(Gk. m.) - Darkness, gloom", "ghnō`mē\n\n(Gk. f.) - Opinion, thought, judgement", "ghnō`sis\n\n(Gk. f.) - Knowledge"]),
                 words(sectionName: "Go", coptic: ["Golgo;a", "Gomorra", "gonato"], english: ["gholghothå\n\n(Heb. f.) - Calvary, Golgotha", "ghomorrå\n\n(Heb.) - Gomorrah", "ghonå`to\n\n(Gk.) - Knee"]),
                 words(sectionName: "Gr", coptic: ["grammateuc", "grammatiky", "gravy"], english: ["gråmmå`tevs\n\n(Gk. m.) - Scribe, secretary", "gråmmå`tikē\n\n(Gk. f.) - Grammar", "ghrå`fē\n\n(Gk. f.) - Writing, drawing, book"]),
                 words(sectionName: "Gw", coptic: ["Gwg"], english: ["gōg\n\nGog"]),

        ]


    

    override func didReceiveMemoryWarning() 
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    

    // MARK: - Table view data source

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

        cell?.textLabel?.text = array[indexPath.section].coptic[indexPath.row]
        cell?.detailTextLabel?.text = array[indexPath.section].english[indexPath.row]
        cell?.textLabel?.font = UIFont(name:"CS Avva Shenouda", size:30)
        cell?.detailTextLabel?.font = UIFont(name: "Constantia", size:25)
        cell?.textLabel?.numberOfLines = 0
        cell?.detailTextLabel?.numberOfLines = 0
        cell?.textLabel?.textColor = UIColor.black
        cell?.detailTextLabel?.textColor = UIColor.darkGray

        return cell!
    


    override func numberOfSections(in tableView: UITableView) -> Int 
        return array.count
    

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
       return array[section].coptic.count

    

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? 
        return array[section].sectionName

    

    override func sectionIndexTitles(for tableView: UITableView) -> [String]? 
        return indexarray
    

    override var preferredStatusBarStyle: UIStatusBarStyle 
        return .lightContent
    

    override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
    
        let header = view as! UITableViewHeaderFooterView
        header.textLabel?.font = UIFont(name: "CS Avva Shenouda", size: 25)!
        header.textLabel?.textColor = UIColor.black
        header.backgroundView?.backgroundColor = UIColor.lightGray

    

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
        print("Row \(indexPath.row) selected")
    

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


         else 


        

    



【问题讨论】:

您到底想要什么发布过滤结果的屏幕截图。 (正如您声明过滤数组但未在 tableview 中使用) 假设我输入“gal”输出是什么 好吧,即使我添加了解决方案希望它对你有用.. 【参考方案1】:

我试图找出您的问题希望您希望以下代码得到输出

//
//  ViewController.swift
//  Testing
//
//  Created by Jaydeep on 28/10/17.


    import UIKit

    class Gamma: UITableViewController, UISearchBarDelegate, UISearchResultsUpdating,UISearchControllerDelegate 


        struct words 

            var coptic : [String]!
            var english : [String]!
        

        var array = [words]()
        var filtered = [words]()
        var filtered2 = UITableViewController()



        let searchController = UISearchController(searchResultsController: nil)




        override func viewDidLoad() 
            super.viewDidLoad()


            let defaultTextAttribs = [NSAttributedStringKey.font.rawValue: UIFont.systemFont(ofSize: 17), NSAttributedStringKey.foregroundColor.rawValue:UIColor.black]


            UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = defaultTextAttribs as Any as! [String : Any]


            self.navigationController?.navigationBar.tintColor = UIColor.white


            searchController.searchBar.delegate = self
            searchController.searchResultsUpdater = self
            searchController.hidesNavigationBarDuringPresentation = false
            searchController.dimsBackgroundDuringPresentation = false
            searchController.delegate = self

            self.navigationItem.titleView = searchController.searchBar

            tableView.rowHeight = UITableViewAutomaticDimension
            tableView.estimatedRowHeight = 400
            tableView.sectionHeaderHeight = 40
            tableView.sectionIndexBackgroundColor = UIColor.clear
            tableView.sectionIndexMinimumDisplayRowCount = 15


            array = [words(coptic: ["Gabriyl", "gaza", "gazovulakion", "gala", "galynyc", "Galile`a", "galileoc", "gamoc", "gar"], english:
                ["ghabriyēl \n\n(Heb.) - Gabriel", "ghå`zå\n\n(f.) - Treasure,money chest", "ghåzo`filåk`yon\n\n(Gk.) - Treasury", "ghå`lå\n\n(Gk. m.) - Milk", "ghålēnēs\n\n(Gk. f.) - Gentle, calm", "ghålilā`å\n\nGalilee", "ghålilā`os\n\n(adj.) - Galilean", "ghåmos / gåmos\n\n(Gk. m.) - Wedding, marriage", "ghår\n\n(Gk. conj.) - For, because"]),
                     words(coptic: ["geenna", "gene`a", "genecic", "genneoc", "gennyma", "gennycic", "gennytyc", "gennytria", "genoc", "Gewrgioc"], english: ["ge`ā`nå\n\n(Heb.) - Gehenna, Hades", "gene`å\n\n1. (Gk. f.) - Generation\n\n2. (Gk. f.) - New, recent", "genesis\n\n(Gk. f.) - Birth, start, inception", "gennā`os\n\n(Gk. adj.) - Brave, noble, honorable, good", "gennē`må\n\n(Gk. m.) - Offspring, product", "gennē`sis\n\n(Gk. f.) - Birth, generation", "gennē`tēs\n\n(Gk. m.) - Parent, generator", "gennēt`riyā\n\n(Gk. f.) - Parent, generator", "gā`nos\n\n(Gk. m.) - Race, tribe", "ge`ōrgi`yos\n\nGeorge"]),
                     words( coptic: ["gy"], english: ["gē\n\n(Gk. f.) - Earth, ground, land"]),
                     words(coptic: ["gnovoc", "gnwmy", "gnwcic"], english: ["ghno`fos\n\n(Gk. m.) - Darkness, gloom", "ghnō`mē\n\n(Gk. f.) - Opinion, thought, judgement", "ghnō`sis\n\n(Gk. f.) - Knowledge"]),
                     words(coptic: ["Golgo;a", "Gomorra", "gonato"], english: ["gholghothå\n\n(Heb. f.) - Calvary, Golgotha", "ghomorrå\n\n(Heb.) - Gomorrah", "ghonå`to\n\n(Gk.) - Knee"]),
                     words( coptic: ["grammateuc", "grammatiky", "gravy"], english: ["gråmmå`tevs\n\n(Gk. m.) - Scribe, secretary", "gråmmå`tikē\n\n(Gk. f.) - Grammar", "ghrå`fē\n\n(Gk. f.) - Writing, drawing, book"]),
                     words( coptic: ["Gwg"], english: ["gōg\n\nGog"]),

            ]
            filtered = array


        
        func searchBarCancelButtonClicked(_ searchBar: UISearchBar) 
            searchBar.text = ""
            // Hide the cancel button
            searchBar.showsCancelButton = false
            filtered = array
            tableView.reloadData()
        
        override func didReceiveMemoryWarning() 
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        

        // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int 
    if filtered.count > 0

    
        return filtered.count
    
    else
    
        return 0
    

        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
            let cellIdentifier = "cell"
            var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
            if cell == nil
            
                cell = UITableViewCell(style: UITableViewCellStyle.value2, reuseIdentifier: cellIdentifier)
            
            cell?.textLabel?.text = filtered[indexPath.section].coptic[indexPath.row]
            cell?.detailTextLabel?.text = filtered[indexPath.section].english[indexPath.row]
            cell?.textLabel?.font = UIFont.systemFont(ofSize: 20)
            cell?.detailTextLabel?.font = UIFont.systemFont(ofSize: 15)
            cell?.textLabel?.numberOfLines = 0
            cell?.detailTextLabel?.numberOfLines = 0
            cell?.textLabel?.textColor = UIColor.black
            cell?.detailTextLabel?.textColor = UIColor.darkGray

            return cell!
        

        override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat 
            return UITableViewAutomaticDimension
        


        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 

            if filtered.count > 0
            
                return filtered[section].coptic.count
            
            else
            
            return 0
            
        

        override var preferredStatusBarStyle: UIStatusBarStyle 
            return .lightContent
        

        override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
            print("Row \(indexPath.row) selected")
        

        func updateSearchResults(for searchController: UISearchController) 
            // If we haven't typed anything into the search bar then do not filter the results
            if searchController.searchBar.text! == ""
            
                filtered = array
            
            else
            
                filtered.removeAll()
                for  i:Int in 0 ..< array.count
                    
                        var copticArray:[String] = []
                        var englishArray:[String] = []
                        var tempWord:words = words.init(coptic: [], english: [])


                        let copticCount = array[i].coptic.count
                        for  copticIndex:Int in 0 ..< copticCount
                        
                            if array[i].coptic[copticIndex].lowercased().contains(searchController.searchBar.text!.lowercased())
                            

                                copticArray.append(array[i].coptic[copticIndex])
                                englishArray.append(array[i].english[copticIndex])

                            
                        

                        tempWord.coptic = copticArray
                        tempWord.english = englishArray
                        if (copticArray.count > 0)
                        
                            self.filtered.append(tempWord)
                        
                    
                tableView.reloadData()

            
        


    

【讨论】:

我让它工作了。非常感谢。您是否知道如何更改索引数组的字体? 好的,所以当单元格设置为自定义时,此代码实际上可以工作。但是当单元格设置为副标题时,这是我想要的格式,当我搜索一个单词时它会崩溃。发生这种情况的任何原因? 为了更清楚,我想使用科普特字符串进行过滤并将其显示为单元格文本标签,同时还在详细文本标签中显示相应的英文字符串。这有可能吗? 你的意思是说如果我搜索“Gal”它只显示部分“GA”而不是“GE”即使“GE”部分中有字符串对吗?? 我添加了一张图片供参考。所以想象在“Ga”部分有十个单词。十个单词的科普特语和英语字符串按字母顺序列出。因此,当表格加载时,它会在单元格的顶部写入科普特字符串单词,并在其下方写入英语单词。我希望能够过滤这些部分以查找科普特词并在其下方有相应的英文定义。

以上是关于数组中字符串的 UISearchBar的主要内容,如果未能解决你的问题,请参考以下文章

java中如何创建字符串数组?

java中如何创建字符串数组?

如何从数组中的字符串数组中获取每个值

请教下,怎么查到数组中,某个字符串,在数组中的索引位置?

JS中如何判断一个字符串是一个字符串数组中的一个元素!!?

java中怎么判断字符数组的长度