数组中字符串的UISearchBar [英] UISearchBar of an string within an array

查看:72
本文介绍了数组中字符串的UISearchBar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  // 
// ViewController.swift
//测试
//
//创建者Jaydeep在28/10/17。


导入UIKit

类Gamma:UITableViewController,UISearchBarDelegate,UISearchResultsUpdating,UISearchControllerDelegate {


结构词{

var coptic:[字符串]!
var english:[字符串]!
}

var array = [words]()
varfiltered = [words]()
varfiltered2 = UITableViewController()



让searchController = UISearchController(searchResultsController:nil)




覆盖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 as as as! [String:任何]


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


searchController.searchBar.delegate =自我
searchController.searchResultsUpdater =自我
searchController.hidesNavigationBarDuringPresentation =假
searchController.dimsBackgroundDuringPresentation =假
searchController.delegate =自我

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],英语的:
[ghabriyēl\n\n(希伯来语)-Gabriel, ghå`zå\n\n(f。)-宝藏,钱箱,ghåzo`filåk`yon \n\n(Gk。)-库房, ghå`lå\n\n(Gk。 m。)-牛奶, ghålēnēs\n\n(G。f。)-温柔,镇定, ghålilā`å\n\nGalilee, ghålilā`os\n\n( adj。)-Galilean,ghåmos/ gåmos\n\n(Gk。m。)-婚礼,婚姻, ghår\n\n(Gk。conj。)-对于,因为] ,
个词(复制词:[ geenna, gene`a, genecic, genneoc, gennyma, gennycic, gennytyc, gennytria, genoc, Gewrgioc ,英语:[ ge`ā`nå\n\n(希伯来语-地名,哈德斯), gene`å\n\n1。(Gk。f。)-Generation\n 2n2。(Gk。f。)-新近的, genesis\n\n(Gk。f。)-出生,开始,开始, gennā`os\n\n(Gk 。adj。)-勇敢,高贵,光荣,良好, gennē`må\n\n(G。m。)-后代,产品, gennē`sis\n\n(Gk。f 。)-出生,世代, gennē`tēs\nGn(G。m。)-父母,发电机, gennēt`riyā\n\n(Gk。f。)-父母,发电机, gā`nos\n\n(G。m。)-种族,部落, ge`ōrgi`yos\n\nGeorge]),
个单词(复制:[ gy],英语:[ gē\n\n(Gk。f。)-地球,地面,土地]),
个词(复制词:[ gn ovoc, gnwmy, gnwcic],英语:[ ghno`fos\n\n(Gk。 m。)-黑暗,阴郁, ghnō`mē\n\n(G。f。)-意见,思想,判断, ghnō`sis\n\n(Gk。f。)-知识]),
个单词(复制词:[ Golgo; a, Gomorra, gonato],英语:[ gholghothå\n\n(Heb。f。)-v髅地,Golgotha , ghomorrå\n\n(希伯来语-Gomorrah), ghonå`to\n\n(Gk。-膝盖)),
个单词(coptic:[ grammateuc , grammatiky, gravy],英语:[ gråmmå`tevs\n\n(Gk。m。)-抄写员,秘书, gråmmå`tikē\n\n(Gk。f。 )-语法, ghrå`fē\n\n(Gk。f。)-书写,绘画,书籍]),
个单词(coptic:[ Gwg],英语:[gōg \n\nGog]),

]
筛选=数组


}
func searchBarCancelButtonClicked(_ searchBar:UISearchBar ){
searchBar.text =
//隐藏取消按钮
searchBar.showsCancelButton = false
filtered =数组
tableView.reloadData()
}
覆盖func didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
//处理所有可以重新创建的资源。
}

//标记:-表格视图数据源
覆盖了func numberOfSections(在tableView中:UITableView)-> Int {
如果filter.count> 0

{
return filter.count
}
其他
{
return 0
}
}
覆盖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 =过滤后的[indexPath.section] .english [indexPath.row]
cell?.textLabel?.font = UIFont.systemFont(ofSize:20)
cell?.detailTextLabel?.font = UIFont.systemFont( ofSize:15)
单元格?.textLabel?.numberOfLines = 0
单元格?.detailTextLabel?.numberOfLines = 0
单元格?.textLabel?.textColor = UIColor.black
单元格?.detailTextLabel?.textColor = UIColor.darkGray

返回单元格!
}

覆盖func tableView(_ tableView:UITableView,heightForRowAt indexPath:IndexPath)-> CGFloat {
return UITableViewAutomaticDimension
}


覆盖func tableView(_ tableView:UITableView,numberOfRowsInSection部分:Int)-> Int {

如果filter.count> 0
{
return filter [section] .coptic.count
}
else
{
return 0
}
}

覆盖var preferredStatusBarStyle:UIStatusBarStyle {
return .lightContent
}

覆盖func tableView(_ tableView:UITableView,didSelectRowAt indexPath:IndexPath){ b $ b print( Row \(indexPath.row)selected)
}

func updateSearchResults(for searchController:UISearchController){
//如果没有在搜索栏中输入任何内容,如果searchController.searchBar.text不过滤结果
! ==
{
已过滤=数组
}
否则
{
filtered.removeAll()
for i:Int in 0 ..< array.count
{
var copticArray:[String] = []
var englishArray:[String] = []
var tempWord:words = words.init(coptic:[ ],英语:[])


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

}
}


}


I am trying to create a dictionary type app with section header, title text, and subtitle text. I managed to get everything to work using the following code. The only thing I can't figure out is how to filter the UISearchBar to show the results of the String [Coptic] within the array. Is this even possible the way I organized everything or do I need to restructure? Does anyone have any suggestions?

I left the code for the updateSearchResults blank on the bottom because I don't know what to code.

 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 {


        }

    }


}

解决方案

I try to figure out your problem hope you want the following code to get output

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

            }
        }


    }

这篇关于数组中字符串的UISearchBar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆