【问题标题】:Create tableView section headers corresponding to month创建对应月份的tableView节标题
【发布时间】:2018-08-18 17:29:10
【问题描述】:

我的 NSMutableArray 和我想创建对应月份的 Single 对象。

我的 JSON 对象在下面,您可以在其中看到键名 Month

(
        {
        day = 27;
        month = "Feb 2018";
        title = HOLIDAY;
    },
        {
        day = 28;
        month = "Feb 2018";
        title = PRESENT;
    },
        {
        day = 1;
        month = "MAR 2018";
        title = ABSENT;
    },
        {
        day = 2;
        month = "MAR 2018";
        title = ABSENT;
    }
)

保存对象的代码,我有另一个可变数组,我尝试保存对应月份的对象。

let array = NSMutableArray()
        var index = Int()
        index = 0
        finalArray.removeAll()
        for i in 0 ..< jsonArray.count{
            if (jsonArray[index] as AnyObject).value(forKey: "month") as! String == (jsonArray[i] as AnyObject).value(forKey: "month") as! String{
                array.add(jsonArray[i])
            }else{
                finalArray.append(array)
                array.removeAllObjects()
                array.add(jsonArray[i])
                index = i
            }
        }
        finalArray.append(array)
        print(finalArray) 

输出:复制对象

[ (
            {
            day = 1;
            month = "Mar 2018";
            title = ABSENT;
        },
            {
            day = 2;
            month = "MAR 2018";
            title = ABSENT;
        }),
        ({
            day = 1;
            month = "MAR 2018";
            title = ABSENT;
        },
            {
            day = 2;
            month = "MAR 2018";
            title = ABSENT;
        }
    )]

我想要过滤 JSON 后的这个输出:

[ (
            {
            day = 27;
            month = "FEB 2018";
            title = ABSENT;
        },
            {
            day = 28;
            month = "FEB 2018";
            title = ABSENT;
        }),
        ({
            day = 1;
            month = "MAR 2018";
            title = ABSENT;
        },
            {
            day = 2;
            month = "MAR 2018";
            title = ABSENT;
        }
    )]

【问题讨论】:

  • 显示您预期的输出格式。
  • 我期望的这个输出。 [( { day = 27; month = "Feb 2018"; title = HOLIDAY;​​ }, { day = 28; month = "Feb 2018"; title = PRESENT; }), ( { day = 1; month = "MAR 2018 "; 标题 = 缺席; }, { 天 = 2; 月 = "2018 年 3 月"; 标题 = 缺席; } )]
  • 检查更新的答案!

标签: ios uitableview swift3


【解决方案1】:

我认为代码将是不言自明的,再简单不过了:

class ViewController: UIViewController {

    @IBOutlet var table: UITableView!

    var jsonArray: [[String:Any]] = [
        ["day": 27, "month": "Feb 2018", "title": "HOLIDAY"],
        ["day": 28, "month": "Feb 2018", "title": "PRESENT"],
        ["day": 1, "month": "MAR 2018", "title": "ABSENT"],
        ["day": 2, "month": "MAR 2018", "title": "ABSENT"]
    ]


    var groupedArray = [[String: Any]]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        table.register(UITableViewCell.self, forCellReuseIdentifier: "DataCell")

        //Extract Months
        let months: [String] = Array(Set(jsonArray.map({$0["month"] as! String})))

        print(months)


        //Sort month by name
        let sortedMonths = months.sorted { (month1, month2) -> Bool in
            let formatter = DateFormatter()
            formatter.dateFormat = "MMM yyyy"

            let date1 = formatter.date(from: month1)
            let date2 = formatter.date(from: month2)

            return date1!.compare(date2!) == .orderedAscending
        }

        print(sortedMonths)


        //group data according to months

        for month in sortedMonths {
            var groupedByMonth = [String: Any]()
            let filteredByMonth = jsonArray.filter({ ($0["month"] as! String) == month })

            groupedByMonth["month"] = month
            groupedByMonth["data"]  = filteredByMonth

            groupedArray.append(groupedByMonth)
        }

        print(groupedArray)
    }
}

extension ViewController: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return groupedArray.count
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        let groupedData = groupedArray[section]
        return groupedData["month"] as? String ?? "Section Title"
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let groupedData = groupedArray[section]
        let data: [[String: Any]] = groupedData["data"] as? [[String: Any]] ?? [[:]]
        return data.count
    }

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

        let groupedData = groupedArray[indexPath.section]
        let data: [[String: Any]] = groupedData["data"] as! [[String: Any]]
        let rowData = data[indexPath.row]

        cell.textLabel?.text = rowData["title"] as! String

        return cell
    }
}

【讨论】:

  • 第二部分开始加载数据时发生崩溃致命错误:索引超出范围
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-22
  • 1970-01-01
相关资源
最近更新 更多