gpt4 book ai didi

arrays - 是否可以在 Swift 中将 UITableViewCell 的值 append 到字符串数组?

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

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

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

我在上面提到的stackOverFlow问题的答案中添加了这部分内容:

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

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

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

terminating with uncaught exception of type NSException

然后它转到 appDelegate.swift

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

提前致谢!本吉

最佳答案

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

与其尝试从 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 }

关于arrays - 是否可以在 Swift 中将 UITableViewCell 的值 append 到字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56806111/

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