2016-05-15 3 views
-1

Я пытаюсь отобразить заголовок раздела с месяцем и годом, когда ячейка была создана как текст в заголовке раздела. Это мой код, но он отображает только один заголовок раздела. Любая идея, почему и как я могу заставить ее отображать год и месяц, была создана ячейка?Добавление заголовка таблицы TableViewCell каждый раз, когда создается новая ячейка, отображающая месяц и год - swift

import UIKit 


class PRViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 

    @IBOutlet var tblTasks : UITableView! 

    //For persisting data 
    let defaults = NSUserDefaults.standardUserDefaults() 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     self.tblTasks.reloadData() 
     tblTasks.registerNib(UINib(nibName: "PRTableViewCell", bundle: nil), forCellReuseIdentifier: "PRTableCell") 
     tblTasks.tableFooterView = UIView() 

    } 

    override func viewWillAppear(animated: Bool) { 
     self.tblTasks.reloadData() 
    } 

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


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



     return 1 

    } 


    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
     return "Your PR's" 
    } 

    //Define how our cells look - 2 lines a heading and a subtitle 
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ 
     let identifier = "PRTableCell" 
     var cell: PRTableViewCell! = tableView.dequeueReusableCellWithIdentifier(identifier) as? PRTableViewCell 

     if cell == nil { 
      tableView.registerNib(UINib(nibName: "PRTableViewCell", bundle: nil), forCellReuseIdentifier: identifier) 
      cell = tableView.dequeueReusableCellWithIdentifier(identifier) as? PRTableViewCell 
     } 


//  Assign the contents of our var "items" to the textLabel of each cell 
//  cell.textLabel!.text = taskMgr.tasks[indexPath.row].name 
//  cell.detailTextLabel!.text = taskMgr.tasks[indexPath.row].desc 

     cell.PRLabel.text = taskMgr.tasks[indexPath.row].name 
     cell.NotesLabel.text = taskMgr.tasks[indexPath.row].desc 
     cell.WeightLabel.text = taskMgr.tasks[indexPath.row].weight + "lb" 






     return cell 



    } 

    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath){ 

     if (editingStyle == UITableViewCellEditingStyle.Delete){ 

      taskMgr.removeTask(indexPath.row) 
      tblTasks.reloadData() 
     } 


     func numberOfSectionsInTableView(tableView: UITableView) -> Int { 

      // #warning Incomplete implementation, return the number of sections 

      let numberOfSections = taskMgr.tasks.count 



      return numberOfSections 
     } 





    } 
+0

Вы получаете только один заголовок раздела для каждого раздела. Изображение, которое вы связали, похоже, отображает две ячейки в одном разделе, и только один заголовок раздела. Чтобы отобразить дату, вам необходимо получить дату, которая представляет все ячейки в этом разделе из вашего источника данных. Затем используйте 'NSDateFormatter' для создания' String', а затем верните это 'String'. Аналогично примерно так: 'let formatter = NSDateFormatter(); formatter.dateStyle = .ShortStyle; formatter.timeStyle = .NoStyle; let dateString = formatter.stringFromDate (sectionHeaderDate); return dateString' –

+0

@RoboticCat Я хочу отображать каждую ячейку в отдельном разделе. затем используйте дату, когда ячейка была добавлена ​​как текст заголовка раздела? Поместил бы это в переопределяющий func-метод? –

+0

Верните правильное количество «разделов» (из вашей модели) в 'numberOfSectionsInTableView:' и верните '1' в' tableView: numberOfRowsInSection: '. Затем установите правильную информацию для каждой ячейки в таблице table: cellForRowAtIndexPath: '. Наконец, в 'tableView: titleForHeaderInSection:' получите дату создания для этого раздела и отформатируйте его, как описано выше. –

ответ

0

Вот один из способов сделать это. Обратите внимание, что этот код предполагает, что данные вашей ячейки находятся в массиве с именем «cellArray». Он отображает дату, которая начинается с сегодняшнего дня и возвращается один день для каждого раздела. Очевидно, вам нужно будет подставить свои даты.

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

func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return self.cellArray.count 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath) 

    // TODO: configure cell for display using self.cellArray[indexPath.section] 

    return cell 
} 

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
    let df = NSDateFormatter() 
    df.dateStyle = .MediumStyle 
    df.timeStyle = .NoStyle 

    // TODO: determine the actual date 
    let displayDate = NSDate().dateByAddingTimeInterval(Double(section * -86400)) 

    return df.stringFromDate(displayDate) 
} 
0

Код примера ниже (код явно не проверен). Я предположил, что есть свойство dateCreated, содержащее NSDate в объектах, хранящихся в вашем массиве tasks.

Пример кода:

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

    return 1 
} 

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

    let formatter = NSDateFormatter() // This is slightly inefficient for a large number of rows because setting up NSDateFormatter is expensive. You could make this a property. 
    formatter.dateStyle = .ShortStyle 
    formatter.timeStyle = .NoStyle 

    let sectionHeaderDate = taskMgr.tasks[section].dateCreated 

    let dateString = formatter.stringFromDate(sectionHeaderDate) 
    return dateString 
} 

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

    let identifier = "PRTableCell" 
    var cell: PRTableViewCell! = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath:idx) as? PRTableViewCell // You must register a class or nib file using the registerNib:forCellReuseIdentifier: or registerClass:forCellReuseIdentifier: method before calling this method (http://stackoverflow.com/q/12737860/558933). 

    cell.PRLabel.text = taskMgr.tasks[indexPath.row].name 
    cell.NotesLabel.text = taskMgr.tasks[indexPath.row].desc 
    cell.WeightLabel.text = taskMgr.tasks[indexPath.row].weight + "lb" // Note iOS 9 allows you to localise weights rather than hard-coding "lb" or "kg". You should look at the documentation. 

    return cell 
} 

func numberOfSectionsInTableView(tableView: UITableView) -> Int { 

    let numberOfSections = taskMgr.tasks.count 
    return numberOfSections 
} 

Чтобы добавить новый «раздел» в UITableView необходимо добавить новые данные в массив taskMgr.tasks, а затем либо перезагрузить таблицу или обновления только добавленные строки. Оберните эти строки кода в tblTasks.beginUpdates и tblTasks.endUpdates. Аналогично для удаления.

+0

Хорошо. Я внедрил код, который вы мне дали, и понял, как это работает, и как мне нужно подключить его к моим основным данным. Теперь я новичок в работе с NSDate. Если я правильно понимаю, мне нужно создать свойство dateCreated, которое содержит текущую дату в месяцах/году в качестве NSDate и хранить его в массиве задач, поэтому, когда он вызывается, он добавит dateSreated NSDate в качестве заголовка раздела. Спасибо за помощь! –

+0

В принципе да. Вам нужно новое свойство dateCreated в ваших объектах в вашем массиве (и в вашей модели Core Data). Когда вы создаете объект в Core Date (или массив в зависимости от того, как вы его кодировали), вам нужно установить 'dateCreated' в текущую дату (например,' newObject.dateCreated = NSDate() '). –

+0

Мой вопрос в том, где я могу поместить код newObject.dateCreated = NSDate()? В моей viewdidload для viewcontroller или в классе, который управляет всеми моими основными данными? –

Смежные вопросы