【问题标题】:How to find duplicate and show the count in table view如何在表格视图中查找重复项并显示计数
【发布时间】:2019-04-16 04:41:26
【问题描述】:

我有一个类似数组的列表,我需要在表格视图中显示

let data = ["a", "a", "b", "c"]

在我的表格视图中,我需要显示每一行中的所有字符串。我完成了。但我需要找到重复项,并且需要更新计数,比如说。在我的数组中,我有a 作为2 counts

所以在我的表格视图中我需要显示像

a(2)
b
c

任何帮助将不胜感激。谢谢

【问题讨论】:

标签: ios arrays swift xcode uitextfield


【解决方案1】:
class TableVC: UIViewController {

    //MARK: - Outlet & Properties
    let data = ["a", "a", "b", "c"]
    var unique = [String]()

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()


        // Do any additional setup after loading the view.
        tableView.dataSource = self
        unique = Array(Set(data)) // Here you will get Unique Elements of Array
    }

}

//MARK: - UITableView datasource
extension TableVC : UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return unique.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! tableCell
        cell.label.text = unique[indexPath.row] + " " +  String(data.filter{$0 == unique[indexPath.row]}.count)

        print(data.filter{$0 == unique[indexPath.row]}.count) // Here you will get COUNT of an Element.
        return cell
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    • 2021-02-22
    相关资源
    最近更新 更多