草庐IT

swift - TableView 在 Swift 中永久重新排序

coder 2023-09-17 原文

我有一个简单的 tableView 在我的应用程序中运行,带有重新排序 tableViewCell 函数。当我尝试重新排序单元格时。重新排序有效。但是当我关闭应用程序并重新打开它时,单元格顺序恢复正常。我想知道如何保存swift 中的新订单单元格。我的简单代码如下没什么特别的,它是一个简单的表格 View ....

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

  @IBOutlet var tableView: UITableView!


  var tableData: [String] = ["Argentina", "Brazil", "Australia","Austria", "Chile", "Denmark","Colombia", "Denmark", "Czech Republic","Egypt", "Ireland", "Germany","Hong Kong", "Netherlands", "Mexico","Poland", "Switzerland", "Panama","United Arab Emirates", "Belgium", "Armenia"]

  override func viewDidLoad() {
    super.viewDidLoad()


    self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")


    self.tableView.reloadData()

  }

  // Toggle editing mode on/off
  @IBAction func reorderItems(sender: AnyObject) {

    if(tableView.editing == true) {
        tableView.setEditing(false, animated: true)
    } else {
        tableView.setEditing(true, animated: true)
    }

  }

  // Set editing mode to show 3 bars on right hand side
  func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
    return UITableViewCellEditingStyle.None
  }


  func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
  }


  func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return false
  }

  func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {

    var itemToMove = tableData[sourceIndexPath.row] 
    tableData.removeAtIndex(sourceIndexPath.row)
    tableData.insert(itemToMove, atIndex: destinationIndexPath.row)

    self.tableView.reloadData()

  }

  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.tableData.count
  }

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

    var cell: UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

    cell.textLabel?.text = self.tableData[indexPath.row]

    return cell
  }

  func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    println("Row \(indexPath.row) selected")
  }
}

谢谢...

最佳答案

要保留自定义顺序,您需要将数组保存为用户默认值。
虽然 NSUserDefaults 不推荐用于大型数据集,但让我们在此示例代码中使用它。

应用委托(delegate)

  • didFinishLaunchingWithOptions 中添加 3 行以注册默认值。

    let countries = ["Argentina", "Brazil", "Australia","Austria", "Chile", "Denmark","Colombia", "Denmark", "Czech Republic","Egypt", "Ireland", "Germany","Hong Kong", "Netherlands", "Mexico","Poland", "Switzerland", "Panama","United Arab Emirates", "Belgium", "Armenia"]
    let defaultValues = ["countries" : countries]
    NSUserDefaults.standardUserDefaults().registerDefaults(defaultValues)
    

View Controller

  • 声明tableData为空数组。

    var tableData = [String]()
    
  • viewWillAppear中添加

    let defaults = NSUserDefaults.standardUserDefaults()
    tableData = defaults.objectForKey("countries") as! [String]
    tableView.reloadData()
    
  • 将方法 reorderItems 替换为

    @IBAction func reorderItems(sender: AnyObject) {
    
      if tableView.editing == true {
         tableView.setEditing(false, animated: true)
         let defaults = NSUserDefaults.standardUserDefaults()
         defaults.setObject(tableData , forKey: "countries")
      } else {
         tableView.setEditing(true, animated: true)
      }
    }
    

关于swift - TableView 在 Swift 中永久重新排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35398094/

有关swift - TableView 在 Swift 中永久重新排序的更多相关文章

  1. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  2. ruby-on-rails - active_admin 目录中的常量警告重新声明 - 2

    我正在使用active_admin,我在Rails3应用程序的应用程序中有一个目录管理,其中包含模型和页面的声明。时不时地我也有一个类,当那个类有一个常量时,就像这样:classFooBAR="bar"end然后,我在每个必须在我的Rails应用程序中重新加载一些代码的请求中收到此警告:/Users/pupeno/helloworld/app/admin/billing.rb:12:warning:alreadyinitializedconstantBAR知道发生了什么以及如何避免这些警告吗? 最佳答案 在纯Ruby中:classA

  3. ruby - 在 Ruby 中重新分配常量时抛出异常? - 2

    我早就知道Ruby中的“常量”(即大写的变量名)不是真正常量。与其他编程语言一样,对对象的引用是唯一存储在变量/常量中的东西。(侧边栏:Ruby确实具有“卡住”引用对象不被修改的功能,据我所知,许多其他语言都没有提供这种功能。)所以这是我的问题:当您将一个值重新分配给常量时,您会收到如下警告:>>FOO='bar'=>"bar">>FOO='baz'(irb):2:warning:alreadyinitializedconstantFOO=>"baz"有没有办法强制Ruby抛出异常而不是打印警告?很难弄清楚为什么有时会发生重新分配。 最佳答案

  4. ruby-on-rails - 需要帮助最大化多个相似对象中的 3 个因素并适当排序 - 2

    我需要用任何语言编写一个算法,根据3个因素对数组进行排序。我以度假村为例(如Hipmunk)。假设我想去度假。我想要最便宜的地方、最好的评论和最多的景点。但是,显然我找不到在所有3个中都排名第一的方法。Example(assumingthereare20importantattractions):ResortA:$150/night...98/100infavorablereviews...18of20attractionsResortB:$99/night...85/100infavorablereviews...12of20attractionsResortC:$120/night

  5. ruby - 将全局 $stdout 重新分配给控制台 - ruby - 2

    我正在尝试将$stdout设置为临时写入一个文件,然后返回到一个文件。test.rb:old_stdout=$stdout$stdout.reopen("mytestfile.out",'w+')puts"thisgoesinmytestfile"$stdout=old_stdoutputs"thisshouldbeontheconsole"$stdout.reopen("mytestfile1.out",'w+')puts"thisgoesinmytestfile1:"$stdout=old_stdoutputs"thisshouldbebackontheconsole"这是输出。r

  6. ruby-on-rails - 在具有 ActiveRecord 条件的相关模型中按字段排序 - 2

    我正在尝试按Rails相关模型中的字段进行排序。我研究的所有解决方案都没有解决如果相关模型被另一个参数过滤?元素模型classItem相关模型:classPriority我正在使用where子句检索项目:@items=Item.where('company_id=?andapproved=?',@company.id,true).all我需要按相关表格中的“位置”列进行排序。问题在于,在优先级模型中,一个项目可能会被多家公司列出。因此,这些职位取决于他们拥有的company_id。当我显示项目时,它是针对一个公司的,按公司内的职位排序。完成此任务的正确方法是什么?感谢您的帮助。PS-我

  7. ruby - Faye WebSocket,关闭处理程序被触发后重新连接到套接字 - 2

    我有一个super简单的脚本,它几乎包含了FayeWebSocketGitHub页面上用于处理关闭连接的内容:ws=Faye::WebSocket::Client.new(url,nil,:headers=>headers)ws.on:opendo|event|p[:open]#sendpingcommand#sendtestcommand#ws.send({command:'test'}.to_json)endws.on:messagedo|event|#hereistheentrypointfordatacomingfromtheserver.pJSON.parse(event.d

  8. ruby - 按数字(从大到大)然后按字母(字母顺序)对对象集合进行排序 - 2

    我正在构建一个小部件来显示奥运会的奖牌数。我有一个“国家”对象的集合,其中每个对象都有一个“名称”属性,以及奖牌计数的“金”、“银”、“铜”。列表应该排序:1.首先是奖牌总数2.如果奖牌相同,按类型分割(金>银>铜,即2金>1金+1银)3.如果奖牌和类型相同,则按字母顺序子排序我正在用ruby​​做这件事,但我想语言并不重要。我确实找到了一个解决方案,但如果感觉必须有更优雅的方法来实现它。这是我做的:使用加权奖牌总数创建一个虚拟属性。因此,如果他们有2个金牌和1个银牌,加权总数将为“3.020100”。1金1银1铜为“3.010101”由于我们希望将奖牌数排序为最高的,因此列表按降序排

  9. ruby-on-rails - 在不重新查询数据库的情况下重新排序 Rails 中的事件记录? - 2

    例如,假设我有一个名为Products的模型,并且在ProductsController中,我有以下代码用于product_listView以显示已排序的产品。@products=Product.order(params[:order_by])让我们想象一下,在product_listView中,用户可以使用下拉菜单按价格、评级、重量等进行排序。数据库中的产品不会经常更改。我很难理解的是,每次用户选择新的order_by过滤器时,rails是否必须查询,或者rails是否能够以某种方式缓存事件记录以在服务器端重新排序?有没有一种方法可以编写它,以便在用户排序时rails不会重新查询结果

  10. ruby - 如何使用 readline 支持重新安装 ruby​​? - 2

    我已经按照https://github.com/wayneeseguin/rvm#installation上的说明通过RVM安装了Ruby.有关信息,我有所有文件(readline-5.2.tar.gz、readline-6.2.tar.gz、ruby-1.9.3-p327.tar.bz2、rubygems-1.8.24.tgz、wayneeseguin-rvm-stable.tgz和yaml-0.1.4.tar.gz)在~/.rvm/archives目录中,我不想在任何目录中重新下载它们方式。当我这样做时:sudo/usr/bin/apt-getinstallbuild-essent

随机推荐