我的任務是做類似MasterDetailApplication
,當我按下按鈕(firstViewController
)當前日期應保存在我的tableView
(secondViewController
)。當我這樣做時,新的日期應該高於最後一個日期。 MasterDetailApplication
這樣的作品是我想要的,但有相同的tableVieController
按鈕。我想我應該使用atIndex : 0
,但我不知道如何使用它。如何在TableView中設置新對象,swift?
Parameters.swift:
import UIKit
var param: Parameters = Parameters()
struct data{
var timer = NSString()
}
class Parameters: NSObject {
var datas = [data]()
func passingData(timer: NSString)
{
datas.append(data(timer: timer))
}
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
var counter = 0
var timer = NSTimer()
@IBOutlet weak var counterLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
counterLabel.text = String(counter)
timer = NSTimer.scheduledTimerWithTimeInterval(1,target:self, selector: ("update"),userInfo: nil, repeats :true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func update(){
counterLabel.text = String(++counter)
if counter == 50 {
timer.invalidate()
}
}
@IBAction func pressedButton(sender: UIButton) {
param.passingData(counterLabel.text!)
}
}
TableViewController.swift:
import UIKit
class TableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate{
var data = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
}
/*
func insertNewObject(sender: AnyObject) {
data.insertObject(NSDate(), atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
*/
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return param.datas.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("default", forIndexPath: indexPath) as UITableViewCell
let date = NSDateFormatter()
date.dateFormat = "yyyy-MM-dd\nhh:mm:ss"
cell.detailTextLabel?.text = param.datas[indexPath.row].timer
cell.textLabel.text = "\(date.stringFromDate(NSDate()))"
return cell
}
}
其實我知道如何做MasterDetailApplication但看我有ViewController和TableViewController。當我按下ViewController中的按鈕時,我移動到TableViewController,然後我的信息被保存在表格中。我的問題是如何做到這一點,當我從我的TableViewController回來,然後再次按下按鈕和一個新的信息保存在最後一個。我在按下按鈕的階段,我移動到TableViewController和我的數據保存在tableView中,但當我再次這樣做時,我的新數據保存在舊數據下。如何改變它? – Tannis 2014-11-06 21:23:44
在MasterDetailApplication這種情況下工作正常。新信息保存在舊信息之上。我認爲這行代碼是有責任的:(NSDate(),atIndex:0)。我怎樣才能把它放到我的代碼中? – Tannis 2014-11-06 21:26:57
在tableViewController中創建一個私有數組。在該數組中插入數據應始終在索引0處。不要附加到數組。在索引0處使用insert。 – 2014-11-06 21:27:08