[英]UITableView Error, Swift, JSON
我正在使用Swift上的业务应用程序课程,并且无法运行我的代码。 我想我已经准备好了所有正确的代码来运行此代码。 我有一个JSON文件,我必须将其导入到应用程序中并将数据从json文件推入tableView中。 “ func tableView”中出现了问题,但我无法弄清楚。 任何帮助表示赞赏:)
我添加了我的代码以及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")
因此,请确保故事板上的单元格标识符为movieTable
,如代码所示。
点2
第二点是您在代码textLabel
和detailTextLabel
中使用了默认的单元格标签,而在情节detailTextLabel
中则表明您已经设置了自定义标签。 无处使用。 因此,根据您的代码,未使用情节提要中的标签。 因此,删除该表并将单元格样式设置为SubTitle
以使用以下代码。
myCell?.textLabel?.text = movies[indexPath.row].MOVIENAME
myCell?.detailTextLabel?.text = movies[indexPath.row].DIRECTORNAME
点3
如果要以自定义方式使用单元格中的标签,则可以创建tableview单元格的自定义类。 制作自定义UITableViewCell 。
您是否已使用UITableViewCell标识符注册UITableView ? 在viewDidLoad()
,放入并尝试
YOUR_TABLE_VIEW.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "movieTable")
正如@technerd所说,请确保代码中的故事板中的单元格标识符为movieTable。
希望这可以帮助。
1>您需要检查您的单元格标识符。 在情节提要中设置正确吗? 2>我认为您必须在填写“ [电影]”后重新加载表格视图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.