【问题标题】:Is it posibble in Swift, to append a value of a UITableViewCell to a array of Strings?在 Swift 中是否可以将 UITableViewCell 的值附加到字符串数组?
【发布时间】:2019-11-10 08:46:14
【问题描述】:

我正在制作一个应用程序,您可以在其中将产品名称及其价格存储在 Realm 数据库中,并在 UItableViewController 和另一个 UITableViewController 中显示以仅显示产品名称,如果您按下 Cell,我想要产品名称附加到字符串数组,并且该产品的价格(未在该特定单元格上显示)附加到另一个双精度数组。那可能吗?如果是,我该怎么做?

我在谷歌上搜索并在 StackOverflow 上找到了答案:getting data from each UITableView Cells Swift 但他的回答没有帮助,这就是我写这个问题的原因。

我在上面提到的stackOverFlow上添加了这部分答案:

selectedProductsForSell.append(cell?.value(forKeyPath: item.name) as! String)

但我不知道如何将连接的价格附加到另一个数组

当我在 iPad 上运行应用程序时,当我选择单元格以将值(产品名称是什么)附加到数组时,会出现以下错误:

terminating with uncaught exception of type NSException

然后它转到 appDelegate.swift

关于如何解决这个问题的任何想法以及我上面描述的关于附加名称和价格的任何想法?

提前致谢! 本吉

【问题讨论】:

  • 你的tableview的dataSource是什么?

标签: arrays swift string uitableview append


【解决方案1】:

进入单元格的数据来自您设置的 UITableViewDataSource 委托。因此,您必须已经可以访问这些数据。

与其尝试从 UI 元素中提取数据,不如从源中提取数据。

您可以在选择每个项目时添加此信息,也可以使用 UITableView indexPathForSelectedRows 获取所有选定项目的索引路径列表。

然后您只需在数据源中的这些索引处获取产品

一些指导...

// top of class, as an example
var products: [Product]()
var selectedProducts: [Product]()

// later in your code somewhere, maybe on didSelectRow
let indexPaths = tableView.indexPathsForSelectedRows
selectedProducts = indexPaths.map { products[indexPath.row] }

// if you just need names
let names = selectedProducts.map { $0.name } 

// or a tuple, containing name and price
let data = selectedProducts.map { ($0.name, $0.price) }

// a better option might be a dictionary
var shoppingList = [String, Double]()
selectedProducts.map { shoppingList[$0.name] = $0.price }  

【讨论】:

  • 在哪里以及如何定义 indexPathForSelectedRows?
  • 它是 UITableView 的一个属性,在我的回答中添加了一个基本示例
  • indexPathsForSelectedRows 和 indexPathForSelectedRow 的区别是什么?
  • 什么是地图?
  • 并且 selectedProducts 需要是可以在按下特定按钮后删除的东西,这可能是从 Products 类推断出来的?
【解决方案2】:

您必须使用tableView's dataSource 来获取数据,而不是访问cell

如果您用作tableView's 数据源的model 看起来像这样,

struct Product {
    var name: String
    var price: Double
}

然后,您可以在tableView(_:didSelectRowAt:) 中访问每个productnameprice,就像,

var products = [Product]() //use this as dataSource of the tableView
var names = [String]()
var prices = [Double]()

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let product = self.products[indexPath.row]
    self.names.append(product.name)
    self.prices.append(product.price)
}

【讨论】:

  • 我使用的是 Realm 数据库,而不是结构。所以可能会有所不同
猜你喜欢
  • 2016-03-02
  • 1970-01-01
  • 2019-01-02
  • 1970-01-01
  • 2014-11-19
  • 2015-11-12
  • 1970-01-01
  • 2019-11-08
  • 1970-01-01
相关资源
最近更新 更多