iOS:来自数组的UICollectionView部分,日期为

时间:2018-01-26 15:43:00

标签: ios arrays swift date collectionview

我有array Person。 Person对象在它们之间有许多字段inscriptionDatetimestamp)。我必须使用collectionView从此array创建sections。每个部分都有inscriptionDate标题作为具有此格式dd/mm/yyyy的日期。我必须按array排序inscriptionDate,但没有时间(只有格式dd/mm/yyyy),以便在collectionView中加载数据(考虑到这些部分)。我从另一个问题中发现了solution。但是,如何在执行此操作之前对array进行排序?我该怎么用呢:

order = NSCalendar.currentCalendar().compareDate(now, toDate: olderDate, 
            toUnitGranularity: .Day)

在我的情况下?

4 个答案:

答案 0 :(得分:1)

我同意@Vasilii Muravev,您需要先使用扩展或功能清理using (SqliteConnection db = new SqliteConnection("Filename=sqliteSample.db")) { db.Open(); var tableCommand = "CREATE TABLE IF NOT EXISTS MyTable (Primary_Key INTEGER PRIMARY KEY AUTOINCREMENT, Text_Entry NVARCHAR(2048) NULL)"; var createTable = new SqliteCommand(tableCommand, db); try { createTable.ExecuteReader(); db.Close(); } catch (SqliteException e) { //Do nothing } } 对象。时间戳不是有效的Swift对象btw,除非这是您创建的自定义类。

然后,您可以为dataSource创建字典。我将使用@Vasilii Muravev的扩展名:

timestamp

将为您提供一个字典对象,其中//var myKeys : [Date] = [] let sortedPeople = persons.sorted { $0.inscriptionDate.noTime() < $1.inscriptionDate.noTime() } //break your array into a dictionary([Date : [Person]]) //personsSortedByDateInSections : [Date : [Person]] = [:] for person in sortedPeople { if personsSortedByDateInSections[person.inscriptionDate] != nil { personsSortedByDateInSections[person.inscriptionDate]!.append(person) } else { personsSortedByDateInSections[person.inscriptionDate] = [person] } } myKeys = setKeyArray(personSortedByDateInSections.keys) 个对象按其Person分组(分段)。然后,您只需要填写collectionView委托和数据源方法。

inscriptionDate

更新: 正如您的评论中所述,使用快速字典抓取一系列密钥存在问题(我不认为快速字典在早期版本中存在此问题?我可能是错的)....无论如何解决这个问题我用过这个函数为'keyArray'设置一个类变量。:

override func numberOfSections(in: UICollectionView) -> Int {
    return myKeys.count
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return personsSortedByDateInSections[myKeys[section]].count
}

答案 1 :(得分:0)

假设您的inscriptionDateDate,为什么不能对此进行排序?由于Date符合Comparable所有您需要的是

let sortedByDate = persons.sorted { $0.inscriptionDate < $1.inscriptionDate }

答案 2 :(得分:0)

首先,您需要在排序之前清理时间戳。您可以使用Dateextension Date { func noTime() -> Date! { let components = Calendar.current.dateComponents([.day, .month, .year], from: self) return Calendar.current.date(from: components) } } 扩展名

来实现
let sortedByDate = persons.sorted { $0.inscriptionDate.noTime() < $1.inscriptionDate.noTime() }

然后你只需要按日期排序你的数组:

compareDate

注意。请注意Calendar的{​​{1}}功能,因为它只比较特定组件。如果在此示例中:NSCalendar.currentCalendar().compareDate(now, toDate: olderDate, toUnitGranularity: .Day)您将在不同月份拥有相同的日期,则比较结果将显示日期相同。

答案 3 :(得分:0)

我为你准备了一个代码我觉得这段代码对你有用。

//
//  ViewController.swift
//  sortData
//
//  Created by Bijender singh on 26/01/18.
//  Copyright © 2018 Bijender singh. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

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

    override func viewDidAppear(_ animated: Bool) {

        let myDataArray = NSMutableArray()
        var myDataDic = NSMutableDictionary()

        myDataDic.setValue("Bijender", forKey: "name")
        myDataDic.setValue("1516965600", forKey: "date")
        myDataArray.add(myDataDic)

        myDataDic = NSMutableDictionary()
        myDataDic.setValue("ben", forKey: "name")
        myDataDic.setValue("1516965540", forKey: "date")
        myDataArray.add(myDataDic)

        myDataDic = NSMutableDictionary()
        myDataDic.setValue("Deke", forKey: "name")
        myDataDic.setValue("1516842180", forKey: "date")
        myDataArray.add(myDataDic)

        myDataDic = NSMutableDictionary()
        myDataDic.setValue("Veer", forKey: "name")
        myDataDic.setValue("1516842000", forKey: "date")
        myDataArray.add(myDataDic)

        myDataDic = NSMutableDictionary()
        myDataDic.setValue("Ashfaq", forKey: "name")
        myDataDic.setValue("1515981900", forKey: "date")
        myDataArray.add(myDataDic)


        print(myDataArray)

        let sortedArray = self.sortDataWithDate(arrayData: myDataArray)

        // sortedArray contane array which contan same date array 
        // you can use it according to you
        // sortedArray.count is total diffrent dates in your array
        // and (sortedArray.count[i] as! NSArray).count give you count of data of that date (0 < i < sortedArray.count)
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func sortDataWithDate(arrayData : NSArray) -> NSArray {
        //  var chat: [ChatMessage]!

        let returnArray = NSMutableArray()
        var subArray = NSMutableArray()
        let arrayDate = NSMutableArray()

        for i in 0 ..< arrayData.count {

            let msgDate = self.timeStampToDate(_timestamp: ((arrayData[i] as! NSDictionary).object(forKey: "date") as! String), _dateFormat: "dd/MM/yyyy")

            print("dddt \(msgDate)")

        //    print("date array \(arrayDate)  $$  msgDate \(msgDate)")
            if arrayDate.contains(msgDate) {

                subArray.add(arrayData[i])

            }
            else{
                arrayDate.add(msgDate)
                if arrayDate.count > 1 {
                    returnArray.add(subArray)
                }

                subArray = NSMutableArray()
                subArray.add(arrayData[i])
            }
        }

        if subArray != nil {
            returnArray.add(subArray)
        }

        print(returnArray)
        return returnArray
    }

     func timeStampToDate(_timestamp : String, _dateFormat : String) -> String{

        // _dateFormat = "yyyy-MM-dd HH:mm:ss.SSSS"

        var date = Date(timeIntervalSince1970: TimeInterval(_timestamp)!)
        date += TimeInterval(Int(TimeZone.current.secondsFromGMT()) as NSNumber)
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone(abbreviation: "GMT") //Set timezone that you want
        dateFormatter.locale = NSLocale.current
        dateFormatter.dateFormat = _dateFormat
        let strDate = dateFormatter.string(from: date)
        return strDate

    }

}

在此代码中,我将数组插入硬编码

(
        {
        date = 1516965600;
        name = Bijender;
    },
        {
        date = 1516965540;
        name = ben;
    },
        {
        date = 1516842180;
        name = Deke;
    },
        {
        date = 1516842000;
        name = Veer;
    },
        {
        date = 1515981900;
        name = Ashfaq;
    }
)

并且输出数组是

(
        (
                {
            date = 1516965600;
            name = Bijender;
        },
                {
            date = 1516965540;
            name = ben;
        }
    ),
        (
                {
            date = 1516842180;
            name = Deke;
        },
                {
            date = 1516842000;
            name = Veer;
        }
    ),
        (
                {
            date = 1515981900;
            name = Ashfaq;
        }
    )
)