[英]Reuse Table View variables Swift
這是表格視圖:
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var rowData: NSDictionary = self.tableData[indexPath.row] as NSDictionary
let too: AnyObject = rowData ["time"] as NSString
var name: String = rowData["time"] as String
var formattedPrice: String = rowData["date"] as String
var alert: UIAlertView = UIAlertView()
alert.title = name
alert.message = formattedPrice
alert.addButtonWithTitle("Ok")
alert.show()
println ("hi")
println (too)
}
我需要在另一個視圖控制器中引用這些變量。 我無法在上面適合該聲明:
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "segueTest") {
var svc = segue!.destinationViewController as secondViewController;
svc.toPass = textField.text
}
}
我正在嘗試隔離單元格單擊。 來自http://jamesleist.com/ios-swift-passing-data-between-viewcontrollers/
如果不是很多數據,我在視圖控制器之間傳遞數據的策略是將值存儲在NSUserDefaults
。
設置值 :首次獲取數據時,將其存儲在NSUserDefaults
。
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() //This class variable needs to be defined every class where you set or fetch values from NSUserDefaults
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var rowData: NSDictionary = self.tableData[indexPath.row] as NSDictionary
let too: AnyObject = rowData ["time"] as NSString
var name: String = rowData["time"] as String
var formattedPrice: String = rowData["date"] as String
defaults.setObject(rowData, forKey: "rowData")
defaults.setObject(too, forKey: "too")
defaults.setObject(name, forKey: "name")
defaults.setObject(formattedPrice, forKey: "formattedPrice")
defaults.synchronize() //Call this after you're done editing defaults, it saves your change to the disk
var alert: UIAlertView = UIAlertView()
alert.title = name
alert.message = formattedPrice
alert.addButtonWithTitle("Ok")
alert.show()
println ("hi")
println (too)
}
獲取值 :當需要獲取值時,只需從NSUserDefaults
獲取NSUserDefaults
。
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.dictionaryForKey("rowData") as? NSDictionary
defaults.objectForKey("too") as? String
defaults.objectForKey("name") as? String
defaults.objectForKey("formattedPrice") as? String
這樣做使您可以訪問任何類中的存儲值,並允許數據在應用程序關閉並重新打開后得以保留。 如果要在應用關閉后清除數據,請在AppDelegate applicationWillTerminate(application: UIApplication)
函數中,為先前設置的每個鍵調用removeObjectForKey函數。
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.removeObjectForKey("rowData")
defaults.removeObjectForKey("too")
defaults.removeObjectForKey("name")
defaults.removeObjectForKey("formattedPrice")
defaults.synchronize()
有關NSUserDefaults的有用資料 :
NSUserDefulats
類參考: 在此處鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.