在Swift中的indexPath上保存TableView数组

时间:2016-10-02 04:23:31

标签: arrays swift uitableview

我在我的项目中运行了两个tableView。我已经使用segue成功地将数据从我的第一个tableView传递到第二个tableView控制器。我正在尝试使用NSUserDefaults.Iy部分代码保存我传递给secondViewController的数据...

第一个VC:

npm

第二个VC:

 var tableView: UITableView!
 var DataArray = ["Bus","Helicopter","Truck","Boat","Bicycle","Motorcycle","Plane","Train","Car","S    cooter","Caravan"]
 var sendSelectedData = NSString()


 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
 let indexPath = tableView.indexPathForSelectedRow!
 let currentCell = tableView.cellForRow(at: indexPath) as UITableViewCell!
       // print(indexPath)
       // print(currentCell)

 sendSelectedData = (currentCell!.textLabel?.text)! as String as NSString
 performSegue(withIdentifier: "ShowDetails", sender: indexPath)

}

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let selectedIndex = sender as! NSIndexPath
    let currentCell =  tableView.cellForRow(at: selectedIndex as IndexPath)!
    self.sendSelectedData = (currentCell.textLabel?.text)! as String as NSString
    if segue.identifier == "ShowDetails" {

    let viewController = segue.destination as! SecondController
    viewController.newItem = (self.sendSelectedData as String)  

    }
}

我正在关注https://grokswift.com/uitableview-updates/文章以实现这项功能......

先谢谢。

1 个答案:

答案 0 :(得分:1)

AppDelegate applicationDidFinishLaunching中注册一个空数组作为键" NewArray"的默认值。

let defaultValues = ["NewArray": [String]()]
UserDefaults.standard.register(defaults: defaultValues)

第二个VC 中定义newArray(变量名称应以小写字母开头)也为空String数组

var newArray = [String]()

viewDidLoad中从用户默认值中检索数组,追加新项目,将数组保存回用户默认值并重新加载表格视图

override func viewDidLoad() {
  super.viewDidLoad()

  let defaults = UserDefaults.standard
  newArray = defaults.array(forKey: "NewArray") as! [String]
  newArray.append(newItem)
  defaults.set(newArray, forKey: "NewArray")
  self.tableView?.reloadData()
}
根本不需要{p> beginUpdates()endUpdates()insertRowsAtIndexPath / reloadRowsAtIndexPaths