[英]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.