gpt4 book ai didi

swift - 如何将 For 中的 lets 放入表中

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

我似乎无法弄清楚如何使用 for 并将 for 中的数据添加到表中任何帮助将不胜感激

import UIKit

class ViewController: UIViewController, UITableViewDataSource {

struct Class: Codable {
let prop_id: String
let prop_location: String
let prop_price: String
enum CodingKeys : String, CodingKey {
case prop_id = "prop_id"
case prop_location = "prop_location"
case prop_price = "prop_price"
}
}

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view, typically from a nib.
let url = URL(string: "https://pricepointproperty.co.uk/appServices/service.php")

// Load the URL
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
// If there are any errors don't try to parse it, show the error
guard let data = data, error == nil else { print(error!); return }

let decoder = JSONDecoder()
let classes = try! decoder.decode([Class].self, from: data)

// Print out the classes to the console - try sticking this in a table view :)
for Properties in classes {
print("\t")
let id: String = (Properties.prop_id)
let location: String = (Properties.prop_location)
let price: String = (Properties.prop_price)
print(id)
print(price)
print(location)
}
}).resume()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let myCell = UITableViewCell()
myCell.textLabel?.text = "location"
return myCell
}
}

最佳答案

我认为您的 Class 定义很好,不需要 CodingKeys 枚举,但可以这样保留它。

为了简单起见,您可以在[Class] 类型的ViewController 中声明一个变量,该数组将保存从您的url 获取的数据。当你解码这个数据时,你将它保存到那个变量,例如你可以做这样的事情: self?.myData = try! decoder.decode([Class].self, 来自: data).

myData 变量声明如下:

fileprivate var myData = [Class]() {
didSet {
// All UI related stuff must run on the main thread
DispatchQueue.main.async {
self?.table.reloadData()
}
}
}

使用 didSet 属性观察器是一种在变量更新后重新加载数据的简单方法。

对于表格的数据源,您应该实现几个方法。第一个简单的只用一行代码返回部分中的行数:

return myData.count

以及实现 cellForRowAt 的方法,该方法使单元格出队并在适当的单元格字段上设置信息。要显示的数据在myData数组中,可以用indexPath给数组下标,如下:

let dataRow = myData[indexPath.row]

您可以在 Github 查看一个实现所有这些的非常简单的项目.该项目的单一 View 如下所示:

enter image description here

希望这对您有所帮助。

关于swift - 如何将 For 中的 lets 放入表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58252018/

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