You need to enable JavaScript to run this app. Swift 5结合Firebase实现UITableView用户列表按姓名首字母分区(类似iOS通讯录)
优惠活动
大模型
产品
解决方案
定价
更多

Swift 5结合Firebase实现UITableView用户列表按姓名首字母分区(类似iOS通讯录)

实现通讯录式首字母分区的适配方案

完全基于你现有代码结构修改,不需要引入第三方依赖,效果和系统通讯录完全一致:

第一步:新增分区相关的属性

保留你原有的全量用户数组table作为原始数据源,只在ViewController类里补充分区需要的结构:

class ViewController: UIViewController {
    //MARK: - variables for the textfield search
    @IBOutlet var field: UITextField!
    var filteredTable = [String]()
    
    //MARK: - Variables for the tableview data from Firebase
    var table = [FacStaffInfo]()
    var ref: DatabaseReference!
    
    // 新增分区相关数据结构
    var sectionTitles: [String] = [] // 存储每个分区的首字母标题
    var sectionData: [[FacStaffInfo]] = [] // 二维数组,存储每个分区对应的用户列表

    @IBOutlet weak var Tableview: UITableView!
    // ... 原有viewDidLoad内的初始化逻辑全部保留
}

第二步:新增数据分组处理方法

在ViewController内部添加这个方法,利用iOS原生API实现拼音首字母提取,不需要依赖第三方库:

// 把原始用户列表按姓名首字母分组、排序
private func processUserSectionData() {
    // 重置分区缓存
    sectionTitles.removeAll()
    sectionData.removeAll()
    
    // 用字典做临时分组容器,key为首字母,value为对应字母下的用户列表
    var sectionDict = [String: [FacStaffInfo]]()
    
    for user in table {
        // 提取用户姓名的首字符
        let name = user.name as NSString
        let firstChar = name.substring(to: 1)
        
        // 原生API转写拼音,自动处理中文姓名的拼音提取
        let mutableString = NSMutableString(string: firstChar) as CFMutableString
        CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
        CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
        let pinyinFirst = String(mutableString).uppercased().prefix(1)
        
        // 非英文字母开头的内容统一归到#分区
        let sectionKey: String
        if pinyinFirst >= "A" && pinyinFirst <= "Z" {
            sectionKey = String(pinyinFirst)
        } else {
            sectionKey = "#"
        }
        
        // 把用户加入对应分组
        if sectionDict[sectionKey] == nil {
            sectionDict[sectionKey] = [user]
        } else {
            sectionDict[sectionKey]?.append(user)
        }
    }
    
    // 对每个分区内部的用户按姓名排序
    for key in sectionDict.keys {
        sectionDict[key]?.sort { $0.name < $1.name }
    }
    
    // 对分区本身排序:A-Z在前,#分区排在最后
    let sortedKeys = sectionDict.keys.sorted { (a, b) -> Bool in
        if a == "#" { return false }
        if b == "#" { return true }
        return a < b
    }
    
    // 把排序后的结果赋值给全局分区数组
    sectionTitles = sortedKeys
    sectionData = sortedKeys.map { sectionDict[$0] ?? [] }
    
    // 数据处理完成后刷新列表
    Tableview.reloadData()
}

第三步:修改Firebase数据加载回调

把原有Firebase观察回调里的刷新逻辑调整一下,等全量用户加载完成后触发分组处理:

ref.observe(DataEventType.value, with: {(snapshot) in
    if snapshot.childrenCount > 0 {
        self.table.removeAll()
        
        for user in snapshot.children.allObjects as! [DataSnapshot] {
            let object = user.value as? [String: AnyObject]
            let title = object?["title"]
            let name = object?["name"]
            let email = object?["email"]
            let phone = object?["phone"]
            let office = object?["office"]
            let bio = object?["bio"]

            let user = FacStaffInfo(title: title as! String, name: name as! String, email: email as! String, phone: phone as! Int, office: office as! String, bio: bio as! String)
            self.table.append(user)
        }
        // 新增:所有用户加载完成后,执行分组处理再刷新列表
        self.processUserSectionData()
    }
})

第四步:替换原有TableView数据源方法

把原来单分区实现的DataSource、Delegate方法替换为多分区适配的版本:

extension ViewController: UITableViewDataSource, UITableViewDelegate {
    // 设置分区总数
    func numberOfSections(in tableView: UITableView) -> Int {
        return sectionTitles.count
    }
    
    // 设置每个分区的头标题
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sectionTitles[section]
    }
    
    // 配置右侧快速索引条
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return sectionTitles
    }
    
    // 设置每个分区的行数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sectionData[section].count
    }
    
    // 配置cell内容
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "userCell") as! TableViewCell
        // 从对应分区的数组里取用户数据,替换原来直接按行号从全量数组取值的逻辑
        let user = sectionData[indexPath.section][indexPath.row]
        
        cell.titleLabel?.text = user.title
        cell.nameLabel?.text = user.name
        cell.emailLabel?.text = user.email
        cell.phoneLabel?.text = String(user.phone)
        cell.officeLabel?.text = user.office
        cell.bioLabel?.text = user.bio

        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: "showDetail", sender: self)
    }
    
    // 配置详情页跳转的传值
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showDetail" {
            if let indexPath = Tableview.indexPathForSelectedRow {
                let destinationController = segue.destination as! InfoViewController
                // 替换原来全量数组取值的逻辑,从分区数组里取选中的用户
                destinationController.FacStaffData = sectionData[indexPath.section][indexPath.row]
            }
        }
    }
}

实现后的效果

  • 所有用户会自动按姓名首字母归类到A-Z的分区下,中文姓名会自动转拼音提取首字母分类
  • 非字母开头的姓名、特殊符号开头的内容会自动归类到#分区
  • TableView右侧会出现和系统通讯录一致的快速索引条,点击可以快速跳转到对应分区
  • 每个分区内部的用户会自动按姓名拼音排序
  • 完全保留你原来的自定义Cell、详情跳转逻辑、Firebase加载逻辑,不需要改动其他已写好的模块

小提示:如果后续要适配你现有的搜索框功能,只需要在搜索输入的回调里,把原始table数组替换成过滤后的用户集合,再调用一次processUserSectionData方法,就可以实现搜索结果的同样分区效果,不需要额外写适配逻辑。

内容的提问来源于stack exchange,提问作者MattyJay94

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.25 05:24:05