简体   繁体   English

在核心数据中使用日期属性在表视图控制器中创建节标题

[英]Creating Section Titles in a Table View Controller with date attribute in Core Data

I have a substantially working app at the moment and I'm currently going through a learning process of enhancing this. 我目前有一个实质性工作的应用程序,我目前正在经历一个增强这个的学习过程。 I have a TableViewController which when prompted, asks a user to input some information and when the user clicks save, that information is displayed appropriately in the table view. 我有一个TableViewController,当系统提示时,要求用户输入一些信息,当用户单击“保存”时,该信息会在表格视图中正确显示。

I would like to ask the user to add one more bit of information and that will make up the section. 我想要求用户添加一点信息,这将构成该部分。 This will be the date. 这将是日期。 Think of Instragram; 想想Instragram; before each picture, you have a date, etc. I want to achieve something like that where the entered date makes up the section headers and then displays them in chronological order. 在每张图片之前,你有一个日期等。我想实现类似的东西,其中输入的日期构成节标题,然后按时间顺序显示它们。

I'm still learning so I'm really stuck on how to achieve this. 我还在学习,所以我真的不知道如何实现这一目标。 I already have one array (called transactions) which is responsible for currently displaying everything in the table view. 我已经有一个数组(称为事务),它负责当前在表视图中显示所有内容。

Do I need to create another array to hold the entered dates? 我是否需要创建另一个数组来保存输入的日期?

How would I implement these methods: 我将如何实现这些方法:

sectionIndexTitlesForTableView

tableView:titleForHeaderInSection

I've not done any implementing of sections before and it's throwing me off. 我以前没有做任何部分的实施,它让我失望。

The Transaction Entity has relationships to a few other entities and occasion is one of them. 交易实体与其他几个实体有关系,偶尔就是其中之一。 In the TableCell, I'm successfully displaying the result of transaction.occasion which is calling the Occasion entity and displaying it's name, etc. That Occasion entity also has a dateOfEvent attribute and basically, I want the section titles to display the dateOfEvents with the corresponding rows representing events in that date. 在TableCell中,我成功地显示了transaction.occasion的结果,它调用了Occasion实体并显示了它的名称等。该Occasion实体也有一个dateOfEvent属性,基本上,我希望section titles显示dateOfEvents with表示该日期事件的相应行。

Any help would be much appreciated! 任何帮助将非常感激!

ps I'm not using an NSFetchedResultsController at the moment; ps我目前没有使用NSFetchedResultsController; I know it's easier but I want to learn this way first.. 我知道这更容易,但我想先学习这种方式..

I know it's too late to answer. 我知道回答为时已晚。 Still just thought of posting my opinion here. 还是想到在这里发表我的意见。

Using NSFetchedResultsController is always useful and time saving when we are using core data to store data and tableview to present it. 当我们使用核心数据存储数据和tableview来呈现它时,使用NSFetchedResultsController总是有用且节省时间。

Here is simple scenario like whatsapp, it will group all messages day wise and sort the messages from each group: 这是一个简单的场景,如whatsapp,它将每天对所有消息进行分组,并对每个组中的消息进行排序:

Data model: 数据模型:

Message<<------->Conversation

Message{
    @NSManaged var body: String?
    @NSManaged var seen: NSNumber?
    @NSManaged var time: NSDate?
    @NSManaged var uid: String?
    @NSManaged var conversation: Conversation?

    var sectionTitle: String? {
        //this is **transient** property
        //to set it as transient, check mark the box with same name in data model
        return time!.getTimeStrWithDayPrecision()
    }

}

initialise NSFetchedResultsController as: NSFetchedResultsController初始化为:

    let request = NSFetchRequest(entityName: "Message")
    let sortDiscriptor = NSSortDescriptor(key: "time", ascending: true)
    request.sortDescriptors = [sortDiscriptor]

    let pred = NSPredicate(format: "conversation.contact.uid == %@", _conversation!.contact!.uid!)
    request.predicate = pred

    let mainThreadMOC = DatabaseInterface.sharedInstance.mainThreadManagedObjectContext()
    fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: mainThreadMOC, sectionNameKeyPath: "sectionTitle", cacheName: nil)
    fetchedResultsController.delegate = self

    do {
        try fetchedResultsController.performFetch()
    } catch {
        fatalError("Failed to initialize FetchedResultsController: \(error)")
    }

data source for table view will be: 表视图的数据源将是:

//MARK: Table view data source

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    let sectionInfo = fetchedResultsController.sections![section]
    let n =  sectionInfo.numberOfObjects
    return n
}

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 60

}

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

    let sectionInfo = fetchedResultsController!.sections! as [NSFetchedResultsSectionInfo]
    return sectionInfo[section].name
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let message = fetchedResultsController.objectAtIndexPath(indexPath) as! Message
    let cell = tableView.dequeueReusableCellWithIdentifier(IncomingChatBubbleCell.identifier(), forIndexPath: indexPath) as! IncomingChatBubbleCell
    configureCell(cell, indexPath: indexPath)

    return cell
}

This will give the result like: 这将得到如下结果:

在此输入图像描述

Hope this will help you!!! 希望这个能对您有所帮助!!!


Update 更新
This is example implementation of getTimeStrWithDayPrecision() Date extension method: 这是getTimeStrWithDayPrecision() Date扩展方法的示例实现:

func getTimeStrWithDayPrecision() -> String {
    let formatter = NSDateFormatter()
    formatter.timeStyle = .NoStyle
    formatter.dateStyle = .ShortStyle
    formatter.doesRelativeDateFormatting = true
    return formatter.stringFromDate(self)
}

I was not concerned whether you are using core data or any other data source.My conclusion is that you need to group occasions based on date.For this you have to filter the occasions from your data source(here numberOfOccasions) based on dateOfOccasion attribute. 我不关心您是使用核心数据还是其他任何数据源。我的结论是您需要根据日期对场合进行分组。为此,您必须根据dateOfOccasion属性过滤数据源(此处为numberOfOccasions)的场合。

I am posting some sample code here to group the occasions. 我在这里发布一些示例代码来分组场合。 Declare a dictionary object in header file such as dicOccasions. 在头文件中声明字典对象,例如dicOccasions。

for(int i=0;i< numberOfOccasions;i++)
    {
        if(dicOccasions==nil)dicOccasions = [[NSMutableDictionary alloc] init];
        NSString *key = [NSString stringWithFormat:@"%@",dateOfOccasion];

        NSMutableArray *ArrTemp= (NSMutableArray*)[[dicOccasions objectForKey:key] mutableCopy];
        if(ArrTemp==nil)ArrTemp = [[NSMutableArray alloc] init];
        [ArrTemp addObject:[[numberOfOccasions objectAtIndex:i] copy]];
        [dicOccasions setObject:[ArrTemp mutableCopy] forKey:key];
    }

In the tableview numberOfsections delegate you can use the count of dicOccasions In the tableView numberOfRowsInSection use follwing code. 在tableview numberOfsections委托你可以使用dicOccasions的计数在tableView numberOfRowsInSection中使用follwing代码。

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *key = [self getSalesOrderKey:section];
    NSMutableArray *   Arry = [dicOccasions objectForKey:key];
    if([Arry isKindOfClass:[NSString class]])return 0;
    return [Arry count];
}
-(NSString*)getSalesOrderKey:(int)section
{
    NSArray *arr = [dicOccasions allKeys];
    arr = [arr sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    if (section<arr.count)return [arr objectAtIndex:section];
    return nil;
}

In viewForHeaderInSecion delegate of tableview you can use following code to get the dateOfOccasion 在tableview的viewForHeaderInSecion委托中,您可以使用以下代码来获取dateOfOccasion

NSString *dateOfOccasion = [self getSalesOrderKey:section];

You can display this in a label and display as section header. 您可以在标签中显示它并显示为节标题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM