Относительно TableViews: Как я могу управлять заголовками разделов и строками через классы? - PullRequest
0 голосов
/ 13 января 2019

Итак, я изучал 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]
}

Ответы [ 2 ]

0 голосов
/ 13 января 2019
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
}

Опять же, вы должны установить ячейку на основе раздела.

0 голосов
/ 13 января 2019

Вы можете сделать это различными способами. Самый простой способ - иметь разные массивы для разных разделов (хотя это может быть не лучшим подходом). Затем изменив numberofRowsInSection в зависимости от этого тоже. Давайте посмотрим:

Создать другой массив:

var opcoesSecond: [Opcao] = []

Другой метод развертывания для второго массива, на этот раз позволяет поместить только два объекта:

func gerarOpcoesForSecond(){
    var opcao1: Opcao
    opcao1 = Opcao(nome: "Novo simulado", descricao: "Clique para começar um novo simulado.", section: "phab", segueIdentifier: "A")
    self.opcoesSecond.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.opcoesSecond.append(opcao2)
}

Вызовите оба метода развертывания массива в viewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()
    gerarOpcoes()
    gerarOpcoesForSecond()
}

Тогда в вашем numberofRowsInSection методе:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
        return opcoes.count        
    } else {
        return opcoesSecond.count
    }
}

В вашем cellForRowAt методе:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCell(withIdentifier: "celula", for: indexPath)

    if indexPath.section == 0 {
        cell.textLabel?.text = self.opcoes[indexPath.row].nome
        cell.detailTextLabel?.text = self.opcoes[indexPath.row].descricao
    } else {
        cell.textLabel?.text = self.opcoesSecond[indexPath.row].nome
        cell.detailTextLabel?.text = self.opcoesSecond[indexPath.row].descricao
    }
    return cell
}

Опять же, как уже упоминалось в комментариях, двухмерный массив может быть лучше для предотвращения повторения кода, как у нас в cellForRowAt методе.

Но это должно решить вашу проблему.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...