ios - 将 tableview 选择的数据存储到带有键值的数组中
问题描述
我是 swift 的新手,我已经创建了 tableview 选择所有行功能,所以选择取消选择对我来说很好,但现在我想要在 tableview 中选择的数据,所以我尝试用Encodable
下面的方法创建结构模型
class QuotationListDataModel: Encodable{
var id: String?
var quantity: String?
var margin: String?
var created_date: String?
var part_number: String?
var total_price: String?
var freight: String?
var fk_customer_id: String?
init(id: String?,quantity: String?,margin: String?,created_date: String?,part_number: String,total_price: String,freight: String,fk_customer_id: String) {
self.id = id
self.quantity = quantity
self.margin = margin
self.created_date = created_date
self.part_number = part_number
self.total_price = total_price
self.freight = freight
self.fk_customer_id = fk_customer_id
}
}
我想像下面这样
[
{
margin: 20,
quantity: 10
part_number: 15
total_price: 1500
freight: 100
},
{
margin: 20,
quantity: 10
part_number: 15
total_price: 1500
freight: 100
}
]
@IBAction func btnSelectAllTapped(_ sender: UIButton) {
if btnSelectAll.titleLabel?.text == "Select All"{
self.btnSelectAll.setTitle("DeSelect All", for: .normal)
self.btnSelectAll.backgroundColor = UIColor(red: 119/255, green: 119/255, blue: 119/255, alpha: 1)
self.btnShare.isHidden = false
self.arrSelectedIds = quotationSeelctedData.map({ (quotation: QuotationListDataModel) -> String in quotation.id! })
//Here when user select all i want all data into array
self.tblListView.reloadData()
}else{
self.isSelectAll = false
btnSelectAll.setTitle("Select All", for: .normal)
btnSelectAll.backgroundColor = UIColor(red: 0/255, green: 175/255, blue: 239/255, alpha: 1)
self.btnShare.isHidden = true
self.arrSelectedIds.removeAll()
print(arrSelectedIds)
self.tblListView.reloadData()
}
}
所以我想要这样的选定数据,任何人都可以帮我解决它
解决方案
要对行进行编码,您需要添加一个枚举,其中包含您希望成为编码数据一部分的属性到您的类
enum CodingKeys: String, CodingKey {
case margin, quantity, part_number, total_price, freight
}
然后你可以像这样编码它
do {
let data = try JSONEncoder().encode(arr)
} catch {
print(error)
}
需要考虑的一些问题,为什么所有属性都是 String 类型,为什么都是可选的?
推荐阅读
- python - 变量值在单元测试中的函数调用后持续存在
- python - 创建与现有数据集具有相似特征的时间序列数据集
- html - 将引导文本粘贴到左侧
- javascript - 未捕获的错误:无效的挂钩调用。Hooks 只能在函数组件的主体内部调用 - 错误仅在 Electron 中显示
- amazon-timestream - 您如何字符串操作来自时间流的返回结果?
- javascript - Reactjs onClick
- reactjs - 如何播放从烧瓶 send_file 发送的音频文件?
- algorithm - 难以思考分而治之的方法
- c - gem5 系统调用查看陷阱指令
- mysql - 损坏的 mysqld 包阻止在 ubuntu 中进行任何其他安装