gpt4 book ai didi

ios - 重用 Table View 变量 Swift

转载 作者:行者123 更新时间:2023-11-28 09:16:01 26 4
gpt4 key购买 nike

这是 TableView :

   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)
}

我需要在另一个 View Controller 中引用这些变量。我无法将上面的声明放入此:

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/

最佳答案

如果数据不是很多,我用来在 View Controller 之间传递数据的策略是将值存储在 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 中获取即可。

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

这样做可以让您访问任何类中存储的值,并允许数据在应用程序关闭并重新打开后保留。如果你想在app关闭后清除数据,在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 类引用:链接 here .

关于ios - 重用 Table View 变量 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27628594/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com