将按日期分隔的部分添加到Swift中的UITableView [英] Adding sections, separated by dates, to UITableView in Swift

查看:183
本文介绍了将按日期分隔的部分添加到Swift中的UITableView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Swift和iOS编程的完整菜鸟,所以你不得不原谅这个简单的问题。



我创建了一个tableView,它在按下一个按钮时显示数组(字符串)的内容。
现在,我想在tableView部分中按照日期排序这些字符串。



更详细地说:当用户点击按钮时,字符串应该插入到数组的索引0处,并显示在一个具有今天日期标题的部分中。如果数组中的值大于今天的值,那么这些值应显示在该日期的单独部分中。每个部分应该对应一个24小时的日期,并显示当天添加的所有字符串。



以下是我迄今为止所取得的一些示例代码:

  var testArray [String]()
var sectionsInTable [String]()

@IBOutlet weak var testTable:UITableView!

@IBAction func saveButton(sender:AnyObject){

testArray.insert(\(strTest),atIndex:0)
testTable.reloaddata )

}

func numberOfSectionsInTableView(tableView:UITableView) - > int {

return sectionsInTable.count

}

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

return testArray.count

}

func tableView(tableView:UITableView,cellForRowAtIndexPath indexPath:NSIndexPath) - > UITableViewCell {

var cell = UITableViewCell(style:UITableViewCellStyle.Default,reuseIdentifier:Cell)

cell.textLabel.text = String(testArray [indexPath.row])

返回单元格
}

我真的不知道如何管理部分部分。希望有人能指出我正确的方向。谢谢!

解决方案

我通常会用Core Data和NSFetchedResultsController ,因为它具有内置方法来获取部分。 p>

但是,我不会使用Core Data来回答这个问题。代码有点乱七八糟,但我们去...



首先,你必须创建一个存储日期和文本的对象。 testArray将是这些对象的数组,而不是String数组。例如:

  class DateTextItem:NSObject {
var text:String =
var insertDate: NSDate = NSDate()
}

var testArray = [DateTextItem]()

然后当saveButton被命中时,我们将创建并添加DateTextItem对象。我们还将日期添加到sectionsInTable,如果它不存在。

  @IBAction func saveButton(sender:AnyObject ){
let newItem = DateTextItem()
newItem.text =Test \(testArray.count)

//这仅用于开发
/ /增加2个记录之后的日期,所以我们可以按日期测试分组
如果testArray.count> =(testArray.count / 2){
let incrementDate = NSTimeInterval(86400 *(testArray.count / 2 ))
newItem.insertDate = NSDate(timeIntervalSinceNow:incrementDate)
}

testArray.append(newItem)

//下一个位将创建一个日期字符串,并检查它是否在sectionInTable
let df = NSDateFormatter()
df.dateFormat =MM / dd / yyyy
let dateString = df.stringFromDate(newItem.insertDate)

//创建NSSet,以便我们可以使用'containsObject'
让部分:NSSet = NSSet(array:sectionsIn表)

//如果sectionsInTable不包含dateString,然后添加
if!sections.containsObject(dateString){
sectionsInTable.append(dateString)
}

self.tableView.reloadData()
}

接下来,我创建了一个函数来获取项目,因为我们需要它在几个地方。

  func getSectionItems section:Int) - > [DateTextItem] {
var sectionItems = [DateTextItem]()

//循环遍历testArray以获取本节日期的项目
for testArray {
let dateTextItem = item作为DateTextItem
let df = NSDateFormatter()
df.dateFormat =MM / dd / yyyy
let dateString = df.stringFromDate(dateTextItem.insertDate)

//如果项目的日期等于段的日期,然后添加
如果dateString == sectionsInTable [section]为NSString {
sectionItems.append(dateTextItem)
}
}

返回sectionItems
}

最后,在这里是表视图数据源方法看起来像

  // MARK: - 表视图数据源
覆盖func numberOfSectionsInTableView (tableView:UITableView) - > int {
return sectionsInTable.count
}

覆盖func tableView(tableView:UITableView,numberOfRowsInSection部分:Int) - > int {
return self.getSectionItems(section).count
}

覆盖func tableView(tableView:UITableView,cellForRowAtIndexPath indexPath:NSIndexPath) - > UITableViewCell {

//配置单元格
var cell = UITableViewCell(style:UITableViewCellStyle.Default,reuseIdentifier:Cell)

// get本节中的项目
let sectionItems = self.getSectionItems(indexPath.section)
//获取本节中的行的项目
let dateTextItem = sectionItems [indexPath.row]

cell.textLabel.text = dateTextItem.text

返回单元格
}

//打印日期作为标题标题
覆盖func tableView(tableView:UITableView,titleForHeaderInSection部分:Int) - >串? {
return sectionsInTable [section]
}


I'm a complete rookie at Swift and iOS programming so you'll have to forgive the perhaps simple question.

I've created a tableView which displays the contents of an array (strings) at the press of a button. Now, I'd like to "group" these strings in tableView sections, sorted by date.

In more detail: When the user taps the button, the string should be inserted at index 0 of the array and be displayed in a section with a header of todays date. If there's values older than today's date in the array, these should be displayed in a separate section for that date. Each section should correspond to a 24 hour day and display all the strings added during that day.

Here's some sample code of what I've achieved so far:

var testArray[String]()
var sectionsInTable[String]()

@IBOutlet weak var testTable: UITableView!

@IBAction func saveButton(sender: AnyObject) {

testArray.insert("\(strTest)", atIndex: 0)
testTable.reloaddata()

}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {

    return sectionsInTable.count

}

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

    return testArray.count

}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")

    cell.textLabel.text = String(testArray[indexPath.row])        

    return cell
}

I really don't know how to manage the sections part. Hopefully someone can point me in the right direction. Thanks!

解决方案

I would usually do this with Core Data and NSFetchedResultsController since it has built-in methods for getting sections.

However, I'll answer the question without using Core Data. The code is a little messier but here we go...

First, you have to create an object that will store both the date and the text. The testArray will be an array of these objects, instead of a String array. For example:

class DateTextItem: NSObject {
    var text: String = ""
    var insertDate: NSDate = NSDate()    
}

var testArray = [DateTextItem]()

Then when the saveButton is hit, we'll create and add the DateTextItem object. We'll also add the date to the sectionsInTable if it doesn't already exist.

@IBAction func saveButton(sender: AnyObject) {
    let newItem = DateTextItem()
    newItem.text = "Test \(testArray.count)"

    // this is for development only
    // increment the date after 2 records so we can test grouping by date
    if testArray.count >= (testArray.count/2) {
        let incrementDate = NSTimeInterval(86400*(testArray.count/2))
        newItem.insertDate = NSDate(timeIntervalSinceNow:incrementDate)
    }

    testArray.append(newItem)

    // this next bit will create a date string and check if it's in the sectionInTable
    let df = NSDateFormatter()
    df.dateFormat = "MM/dd/yyyy"
    let dateString = df.stringFromDate(newItem.insertDate)

    // create sections NSSet so we can use 'containsObject'
    let sections: NSSet = NSSet(array: sectionsInTable)

    // if sectionsInTable doesn't contain the dateString, then add it
    if !sections.containsObject(dateString) {
        sectionsInTable.append(dateString)
    }

    self.tableView.reloadData()
}

Next, I created a function to get the items in a section since we need it in a couple places.

func getSectionItems(section: Int) -> [DateTextItem] {
    var sectionItems = [DateTextItem]()

    // loop through the testArray to get the items for this sections's date
    for item in testArray {
        let dateTextItem = item as DateTextItem
        let df = NSDateFormatter()
        df.dateFormat = "MM/dd/yyyy"
        let dateString = df.stringFromDate(dateTextItem.insertDate)

        // if the item's date equals the section's date then add it
        if dateString == sectionsInTable[section] as NSString {
            sectionItems.append(dateTextItem)
        }
    }

    return sectionItems
}

Finally, here is what the Table View Data Source methods look like

// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return sectionsInTable.count
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.getSectionItems(section).count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    // Configure the cell...
    var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")

    // get the items in this section
    let sectionItems = self.getSectionItems(indexPath.section)
    // get the item for the row in this section
    let dateTextItem = sectionItems[indexPath.row]

    cell.textLabel.text = dateTextItem.text

    return cell
}

// print the date as the section header title
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return sectionsInTable[section]
}

这篇关于将按日期分隔的部分添加到Swift中的UITableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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