在Core Data中具有date属性的Table View Controller中创建节标题 [英] Creating Section Titles in a Table View Controller with date attribute in Core Data

查看:96
本文介绍了在Core Data中具有date属性的Table View Controller中创建节标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个可以正常使用的应用程序,目前正在学习以增强该功能的学习过程。我有一个TableViewController,当系统提示时,它要求用户输入一些信息,并且当用户单击保存时,该信息会在表视图中正确显示。



我想请用户添加更多信息,这将构成该部分。这将是日期。想起Instragram;在每张图片之前,您都有一个日期,等等。我想要实现类似的功能,其中输入的日期构成了节标题,然后按时间顺序显示它们。



我仍在学习,因此我对如何实现这一目标非常执着。我已经有一个数组(称为事务),该数组负责当前在表视图中显示所有内容。



是否需要创建另一个数组来保存输入的日期?



我将如何实现以下方法:

  sectionIndexTitlesForTableView 

tableView:titleForHeaderInSection

我之前没有执行任何节,这使我失望。



交易实体与其他几个实体有关系,有时就是其中之一。在TableCell中,我成功显示了transaction.occasion的结果,该结果正在调用Occasion实体并显示其名称,等等。该Occasion实体还具有dateOfEvent属性,并且基本上,我希望各节标题显示带有dateOfEvents的内容。代表该日期中事件的相应行。



任何帮助将不胜感激!



p.s。我目前不在使用NSFetchedResultsController;我知道它比较容易,但是我想先学习这种方式。

解决方案

我知道现在回答还为时已晚。仍然只是想在这里发表我的意见。数据以存储数据并用tableview呈现。



这里是诸如whatsapp之类的简单方案,它将按天对所有消息进行分组,并对每个组中的消息进行排序:



数据模型:

 消息<< -------- >会话

消息{
@NSManaged var body:字符串?
@NSManaged变量:NSNumber?
@NSManaged var time:NSDate?
@NSManaged var uid:字符串?
@NSManaged var对话:对话?

var sectionTitle:字符串? {
//这是** transient **属性
//将其设置为瞬态,请在数据模型
返回时间中选中具有相同名称的框!.getTimeStrWithDayPrecision()
}

}

初始化 NSFetchedResultsController 为:

  let request = NSFetchRequest(entityName: Message)
let sortDiscriptor = NSSortDescriptor(键:时间,升序:true)
request.sortDescriptors = [sortDiscriptor]

let pred = NSPredicate(格式: conversation.contact.uid ==%@, _conversation!.contact!.uid! mainThreadMOC,sectionNameKeyPath: sectionTitle,cacheName:nil)
fetchedResultsController.delegate =自我

做{
try fetchedResultsController.performFetch()
} catch {
fatalError(未能初始化FetchedResultsController:\(错误))
}

用于表视图的数据源将是:

  // MARK:表视图数据源

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

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

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

}

func tableView(tableView:UITableView,titleForHeaderInSection部分:Int)->串? {

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

func tableView(tableView:UITableView,cellForRowAtIndexPath indexPath:NSIndexPath)-> UITableViewCell {
让message = fetchedResultsController.objectAtIndexPath(indexPath)为!消息
让cell = tableView.dequeueReusableCellWithIdentifier(IncomingChatBubbleCell.identifier(),forIndexPath:indexPath)为! IncomingChatBubbleCell
configureCell(cell,indexPath:indexPath)

返回单元格
}

这将给出如下结果:





希望这对您有帮助!






更新

这是 getTimeStrWithDayPrecision()日期扩展方法的示例实现:

  func getTimeStrWithDayPrecision()->字符串{
let formatter = NSDateFormatter()
formatter.timeStyle = .NoStyle
formatter.dateStyle = .ShortStyle
formatter.doesRelativeDateFormatting = true
返回formatter.stringFromDate(自我)
}


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.

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; 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.

Any help would be much appreciated!

p.s. I'm not using an NSFetchedResultsController at the moment; 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.

Here is simple scenario like whatsapp, it will group all messages day wise and sort the messages from each group:

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:

    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:

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

这篇关于在Core Data中具有date属性的Table View Controller中创建节标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆