IOS

swift实现tableview分组

2019-02-15  本文已影响1人  瑟闻风倾

1. 界面展示

tableview分组.png

2. 界面设计

界面设计.png

3.具体实现

(1)AnimalTableViewController.swift

//
//  AnimalTableViewController.swift
//  JackUChat
//
//  Created by 徐云 on 2019/2/15.
//  Copyright © 2019 Liy. All rights reserved.
//

import UIKit

class AnimalTableViewController: UITableViewController,UISearchResultsUpdating  {
    
    //数据:字符串数组
    let animals = ["Bear", "Black Swan", "Buffalo", "Camel", "Cockatoo", "Dog", "Donkey", "Emu", "Giraffe", "Greater Rhea", "Hippopotamus", "Horse", "Koala", "Lion", "Llama", "Manatus", "Meerkat", "Panda", "Peacock", "Pig", "Platypus", "Polar Bear", "Rhinoceros", "Seagull", "Tasmania Devil", "Whale", "Whale Shark", "Wombat"]
    var animalsDict = [String: [String] ] ()//初始化用于存储动物的空字典
    var animalSectionTitles = [String] ()//初始化用于存储表的块标题的空数组,块标题是动物名字的首字母
    
    var sc : UISearchController!//1. 定义UISearchController
    var searchResults : [String] = []//定义空数组保存筛选结果
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
        
        //2.UISearchController初始化
        sc = UISearchController(searchResultsController: nil)//结果控制器
        sc.searchResultsUpdater = self
        tableView.tableHeaderView = sc.searchBar
        sc.dimsBackgroundDuringPresentation = false//搜索条背景不变暗
        sc.searchBar.placeholder = "请输入名称进行搜索"//占位符
        //sc.searchBar.tintColor = UIColor.white//前景色
        //sc.searchBar.barTintColor = UIColor.orange//背景色
        sc.searchBar.searchBarStyle = .minimal//透明样式
        
        createAnimalDict()
        
    }

    // MARK: - Table view data source

    //返回Section数量
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        //return animalSectionTitles.count
        return sc.isActive ? 1 : animalSectionTitles.count
    }
    
    //返回每个section的标题
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        //return animalSectionTitles[section]
        return sc.isActive ? "结果" : animalSectionTitles[section]
    }

    //返回每个section的的行数
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        let animalKey = animalSectionTitles[section]
        guard let animalValues = animalsDict[animalKey] else { return 0 }
        //return animalValues.count
        return sc.isActive ? searchResults.count : animalValues.count
    }
    
    //显示表数据
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        let cell = tableView.dequeueReusableCell(withIdentifier: "AnimalCell", for: indexPath)

        let cellId = String(describing: AnimalCell.self)
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! AnimalCell
        
        // Configure the cell...
        
        let animalKey = animalSectionTitles[indexPath.section]
        if let animalValues = animalsDict[animalKey] {
            //cell.animalName?.text = animalValues[indexPath.row]
            let animal = sc.isActive ? searchResults[indexPath.row] : animalValues[indexPath.row]
            cell.animalName?.text = animal
//            let imageFileName = animalValues[indexPath.row].lowercased().replacingOccurrences(of: "", with: "_")
//            cell.animalImage?.image = UIImage(named: imageFileName)
            
        }

        return cell
    }
    
    //右侧索引:返回出现在表视图右边的索引列表中的索引标题,如返回包含从a到Z值的字符串数组.
    override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return animalSectionTitles
    }
    //返回当用户点击特定索引时,表视图应该跳转到的部分索引.
    //    override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
    //        return 0
    //    }
    
    
    // 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 !sc.isActive
    }
    

    /*
    // 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: UITableViewCellEditingStyle, 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.
    }
    */
    
    // MARK: - Search
    
    //当点击搜索条更改搜索文字时被调用
    func updateSearchResults(for searchController: UISearchController) {
        //获取搜索栏文字,筛选后刷新列表
        if var text = searchController.searchBar.text {
            text = text.trimmingCharacters(in: .whitespaces)//忽略前后空格
            searchFilter(text: text)
            tableView.reloadData()
        }
    }
    
    //添加一个筛选器方法:使用Swift数组自带filter方法,返回一个符合条件的新数组
    func searchFilter(text:String) {
        searchResults = animals.filter({ (animal) -> Bool in
            return animal.localizedCaseInsensitiveContains(text)
        })
    }

    
    func createAnimalDict() {
        for animal in animals {
            //得到每一个动物名的第一个字母
            let firstLetterIndex = animal.index(animal.startIndex, offsetBy: 1)
            let animalKey = String(animal[..<firstLetterIndex])//字符串切片到指定索引
            
            //创建字典:动物名的第一个字母被作为字典的键,字典的值为指定键的动物数组
            if var animalValues = animalsDict[animalKey]{
                animalValues.append(animal)
                animalsDict[animalKey] = animalValues//
            }else{
                animalsDict[animalKey] = [animal]//创建新的动物数组添加到已有的动物数组
            }
            
            //从字典关键字中获取表每部分的标题并排序
            animalSectionTitles = [String](animalsDict.keys)//从字典的键中检索表每块的标题
            animalSectionTitles = animalSectionTitles.sorted(by: { $0 < $1 })//sort函数根据所提供的排序闭包的输出返回已知类型的值的排序数组
        }
    }
    


}

(2)

//
//  AnimalCell.swift
//  JackUChat
//
//  Created by 徐云 on 2019/2/15.
//  Copyright © 2019 Liy. All rights reserved.
//

import UIKit

class AnimalCell: UITableViewCell {

    @IBOutlet weak var animalImage: UIImageView!
    @IBOutlet weak var animalName: UILabel!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

备注参考

上一篇下一篇

猜你喜欢

热点阅读