作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我似乎无法弄清楚如何使用 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 如下所示:
希望这对您有所帮助。
关于swift - 如何将 For 中的 lets 放入表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58252018/
我是一名优秀的程序员,十分优秀!