私はこの画面が必要なアプリケーションを作成しています。さテーブルビューのセクションにデータが正しく取り込まれない
var sections = ["Adventure type"]
var categoriesList = [String]()
var items: [[String]] = []
override func viewDidLoad() {
super.viewDidLoad()
categoryTableView.delegate = self
categoryTableView.dataSource = self
Client.DataService?.getCategories(success: getCategorySuccess(list:), error: getCategoryError(error:))
}
func getCategorySuccess(list: [String])
{
categoriesList = list
let count = list.count
var prevInitial: Character? = nil
for categoryName in list {
let initial = categoryName.first
if initial != prevInitial { // We're starting a new letter
items.append([])
prevInitial = initial
}
items[items.endIndex - 1].append(categoryName)
}
for i in 0 ..< count
{
var tempItem = items[i]
let tempSubItem = tempItem[0]
let char = "\(tempSubItem.first)"
sections.append(char)
}
}
func getCategoryError(error: CError)
{
print(error.message)
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sections[section]
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = categoryTableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)
cell.textLabel?.text = self.items[indexPath.section][indexPath.row]
return cell
}
Iはセクションとテーブルビューを使用しているしかし、私は、データ(項目配列)をロードしていますので、このエラーの原因であるreturn self.items[section].count
にランタイムエラーを生成していますその後、セクションの後ろにセクションを配置します。 tableviewが生成された時点で、sectionsとitemsの配列は空です。そのため、エラーが発生します。 私はiOSを初めて使い、tableviewのセクションでデータを調整する方法を理解していません。
- 誰かが私にこれを行うより良い方法を提案できますか?
- サーバコールが返されるアイテムの量がわからない場合、セクションの行数はどのくらいですか?
- また、サーバーコールが失敗し、データが返されない場合は、ケースをカバーしたいと思います。テーブルビューを隠して(とエラーメッセージを表示する)十分でしょうか?
ご協力いただければ幸いです。
var items: [[String]]?
そして、あなたのgetCategorySuccess
の内側にそれをインスタンス化した値でそれを埋める:データソースはオプション行います
dataSourceをnullにすることは無意味ですが、デフォルト値を指定するだけでコードを追加できます – zombie