如何在tableview中过滤部分明智的行? [英] how to filter section wise row in tableview?

查看:18
本文介绍了如何在tableview中过滤部分明智的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 iOS 新手,正在创建基于 JSON 响应的演示应用程序.

I'm new in iOS and creating a demo app on basis of JSON response.

我的查询是我不知道如何明智地编写和过滤行数据部分以在 tableview 上显示.

my query is I don't know how to write and filter row data section wise to show on tableview.

category.json [文件]

category.json [file]

{
    "category": [
        {
            "vName": "Section 0",
            "skill": [
                {
                    "vName": "Section 0 Row 1",
                },
                {
                    "vName": "Section 0 Row 2",
                }
            ]
        },
        {
            "vName": "Section 1",
            "skill": [
                {
                    "vName": "Section 1 Row 1",
                },
                {
                    "vName": "Section 1 Row 2",
                }
            ]
        },
        {
            "vName": "Section 2",
            "skill": [
                {
                    "vName": "Section 2 Row 1",
                },
                {
                    "vName": "Section 2 Row 2",
                }
            ]
        },
        {
            "vName": "Section 3",
            "skill": [
                {
                    "vName": "Section 3 Row 1",
                },
                {
                    "vName": "Section 3 Row 2",
                }
            ]
        }
    ]
}

Response.Swift [文件]

Response.Swift [file]

//
//  Response.swift
//  SectionTableSearchDemo
//

import Foundation
struct Welcome: Codable {
    let category: [Category]
}

struct Category: Codable {
    let vName: String
    let skill: [Skill]

    enum CodingKeys: String, CodingKey {
        case vName,skill
    }
}

struct Skill: Codable {
    let vName: String

    enum CodingKeys: String, CodingKey {

        case vName
    }
}

#SectionTableviewController.swift [文件]

#SectionTableviewController.swift [file]

//
//  SectionTableViewController.swift
//  SectionTableSearchDemo
//

import UIKit


class SectionTableViewController: UITableViewController, UISearchResultsUpdating {

    var cat : Welcome?
    var searchController : UISearchController!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        parseJSON()
        searchControllerSetup()
    }

     private func searchControllerSetup(){
        
        searchController = UISearchController(searchResultsController: nil)
        searchController.searchResultsUpdater = self
    
        navigationItem.searchController = searchController
        navigationItem.hidesSearchBarWhenScrolling = false
    }
    
    // i don't know how to implement and show only skills when search
    func updateSearchResults(for searchController: UISearchController) {
        
    }
    
    private func parseJSON(){
        
        guard let path = Bundle.main.path(forResource: "category", ofType: "json")else{
            return
        }
       
        let url = URL(fileURLWithPath: path)
        
        do {
            let jsonData = try Data(contentsOf: url)
            cat = try JSONDecoder().decode(Welcome.self, from: jsonData)
            if let result = cat {
                print(result)
            }
        } catch  {
            print("Error is \(error)")
        }
        
        
    }
    
    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return  (cat?.category.count)!
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        if let cat = cat {
            return cat.category[section].skill.count
        }else{
            return 0
        }
    }

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

        let text = cat?.category[indexPath.section].skill[indexPath.row].vName
        cell.textLabel?.text = text

        return cell
    }
    
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        let titleText = cat?.category[section].vName
        return titleText
    }
    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // 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.destination.
        // Pass the selected object to the new view controller.
    }
    */

}


以及我对我所做的事情

请帮我弄清楚

谢谢

推荐答案

要搜索模型内的数据,您可以使用过滤器功能.与您在 tableview 单元格中显示数据的方式相同.您可以使用过滤器功能进行搜索,并根据搜索标志显示其中的数据.

To search data inside the model you can use the Filter function. Same way as you are showing data inside tableview cell. You can search using the filter function and show data inside based on the search flag.

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

        guard let searchText = searchText, !searchText.isEmpty else {
            return
        }

        searchData = cat?.category.map({
                        $0.skill.filter({$0.vName == searchText})
                           }).filter({ $0.count > 0 })

        searching = true
        self.searchedSkillsResults = searchData
        tableView.reloadData()
    }

//在这里检查您的搜索是否为真,并显示技能数组,否则搜索为假的原始数组结果.

//Check here if your search is true and show skills array else original array results with search false.

参考链接:如何快速从模型中搜索数据?

//下面的链接可帮助您在嵌套数组中进行搜索.Swift 过滤嵌套数组

//below link help you to search within nested array. Swift Filter Nested Array

我正在运行的示例代码:

My sample code which is working:

import Foundation
struct Welcome: Codable {
   let category: [Category]
}

struct Category: Codable {
    let vName: String
    let skill: [Skill]

    enum CodingKeys: String, CodingKey {
        case vName,skill
    }
}

struct Skill: Codable {
    let vName: String

    enum CodingKeys: String, CodingKey {

         case vName
    }
 }

 var cat : Welcome?

 private func parseJSON(){

    guard let path = Bundle.main.path(forResource: "category", ofType: 
        "json")else{
        return
    }

    let url = URL(fileURLWithPath: path)

    print(url)

    do {
        let jsonData = try Data(contentsOf: url)
        cat = try JSONDecoder().decode(Welcome.self, from: jsonData)
        if let result = cat {
             print(result)
        }
    } catch  {
        print("Error is \(error)")
    }
}

parseJSON()
//print(cat)

let searchText = "Section 0 Row 1"
let result = cat?.category.map({
   $0.skill.filter({$0.vName.lowercased().contains(searchText.lowercased())})
}).filter({ $0.count > 0 })

//output = Optional([[Skill(vName: "Section 0 Row 1")]])

这篇关于如何在tableview中过滤部分明智的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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