gpt4 book ai didi

json - UITableView 错误,Swift,JSON

转载 作者:行者123 更新时间:2023-11-30 11:40:59 25 4
gpt4 key购买 nike

我正在学习 Swift 商业应用程序类(class),但在运行我的代码时遇到问题。我想我已经准备好了所有正确的代码来运行它。我有一个 JSON 文件,必须将其导入应用程序并将数据从 json 文件推送到 tableView 中。 “func tableView”中出现了一些问题,但我无法弄清楚。如有任何帮助,我们将不胜感激:)

I added a screenshot of my code, as well as the main.storyboard

import UIKit

struct Movie : Decodable {
let MOVIENAME : String
let DIRECTORNAME : String
}

class ViewController: UIViewController, UITableViewDataSource,
UITableViewDelegate {
//indicates this is an array of the structure 'Movie'
var movies = [Movie]()

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
UITableViewCell {
let myCell = movieTableView.dequeueReusableCell(withIdentifier:
"movieTable")
myCell?.textLabel?.text = movies[indexPath.row].MOVIENAME
myCell?.detailTextLabel?.text = movies[indexPath.row].DIRECTORNAME
return myCell!
}

@IBOutlet weak var movieTableView: UITableView!

override func viewDidLoad() {
super.viewDidLoad()

// construct path to the file, this tells the system the name of the file and the file type JSON
let path = Bundle.main.path(forResource: "movies", ofType: "json")
let url = URL(fileURLWithPath: path!) //creating url of the file, add "!" to unwrap the path

do {
//'try" is a security measure that basically says, if we dont get successfully create data through the url
let data = try Data(contentsOf: url)
self.movies = try JSONDecoder().decode([Movie].self, from: data)

for eachMovie in self.movies {
print(eachMovie.MOVIENAME)
}
} catch {
print("JSON Error.")
}

movieTableView.delegate = self
movieTableView.dataSource = self
}
}

最佳答案

第 1 点

从代码和屏幕截图来看,您似乎设置了与代码中使用的不同的单元格标识符(猜猜!!)。因此单元格返回 nil 并且应用程序将崩溃。

let myCell = movieTableView.dequeueReusableCell(withIdentifier: 
"movieTable")

因此请确保 Storyboard 中的单元标识符是 movieTable,如代码中所示。

第2点

第二点是您在代码 textLabeldetailTextLabel 中使用单元格的默认标签。而在 Storyboard中,它显示您已设置自定义标签。哪些地方都没有使用。因此,根据您的代码, Storyboard中的标签未使用。因此,删除该表格并将单元格样式设置为 SubTitle 以使用以下代码。

myCell?.textLabel?.text = movies[indexPath.row].MOVIENAME
myCell?.detailTextLabel?.text = movies[indexPath.row].DIRECTORNAME

enter image description here

第3点

如果您想以自定义方式在单元格中使用标签,您可以创建表格 View 单元格的自定义类。 To make custom UITableViewCell .

关于json - UITableView 错误,Swift,JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49291879/

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