Итак, я изучал Swift и пытался использовать TableView с двумя разделами. Дело в том:
Я успешно разработал приложение с использованием TableViewController только с одним разделом и использовал данные из класса «Opcao» для заполнения строк.
Поэтому я решил создать еще один раздел, установив return 2
на override func numberOfSections(in tableView: UITableView) -> Int
, и это сработало, мне действительно нужны были только два раздела.
Моя проблема: в обоих разделах одинаковое количество строк и одинаковое содержание. Как я мог это изменить? Я имею в виду, что я хотел бы, чтобы второй раздел под названием «Teste» имел свои собственные поля ячеек (отличные от первого раздела), но также содержал информацию о классе Opcao.
Имена разделов в моем TableView должны фактически быть атрибутом, называемым "section", а содержимое строк должно быть числом строк в ячейке - это количество объектов с каким типом "section". Что мне делать?
Opcao.swift:
class Opcao {
var nome:String
var descricao: String
var section: String
var segueIdentifier: String
init(nome: String, descricao: String, section: String, segueIdentifier: String){
self.nome = nome //displayed as main value of the cell
self.descricao = descricao //description which goes bellow the cell title
self.section = section // what I though it could be the section tittle which the option belongs to
self.segueIdentifier = segueIdentifier //used for other stuff, not relevant to this situation
}
Части TableViewController.swift:
class TableViewController: UITableViewController {
var opcoes: [Opcao] = []
var titulos: [String] = ["1a Habilitação", "Teste"]
override func viewDidLoad() {
super.viewDidLoad()
gerarOpcoes()
}
func gerarOpcoes(){
//criando opcao 1
var opcao1: Opcao
opcao1 = Opcao(nome: "Novo simulado", descricao: "Clique para começar um novo simulado.", section: "phab", segueIdentifier: "A")
self.opcoes.append(opcao1)
//criando opcao 2
var opcao2: Opcao
opcao2 = Opcao(nome: "Responder livremente", descricao: "Responda diversas perguntas sem tempo limite.", section: "phab", segueIdentifier: "B")
self.opcoes.append(opcao2)
//criando opcao 3
var opcao3: Opcao
opcao3 = Opcao(nome: "Histórico", descricao: "Veja seus últimos resultados.", section: "phab", segueIdentifier: "C")
self.opcoes.append(opcao3)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return opcoes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "celula", for: indexPath)
cell.textLabel?.text = self.opcoes[indexPath.row].nome
cell.detailTextLabel?.text = self.opcoes[indexPath.row].descricao
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return titulos[section]
}