Как я могу получить доступ к переменной внутри структуры, чтобы подсчитать количество элементов, перечисленных в массиве переменной? - PullRequest
0 голосов
/ 15 сентября 2018

Мне нужна помощь, чтобы иметь возможность отображать в строковом формате в заголовке каждого раздела таблицы представление количества перечисленных (ячеек) в массиве sectionData.Какие sectionData перечислены как переменная внутри структуры (cellData).

import UIKit

struct cellData
{
    
    var opened = Bool()
    var title = String()
    var sectionData = [String]()

    
}



class TableViewController: UITableViewController {

    var tableViewData = [cellData]()
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        tableViewData = [cellData(opened: false, title: "Monday, September 10, 2018", sectionData: ["Cell1", "Cell2", "Cell3"]),
                         cellData(opened: false, title: "Tuesday, September 11, 2018", sectionData: ["Cell1", "Cell2", "Cell3"]),
                         cellData(opened: false, title: "Wednesday, September 12, 2018", sectionData: ["Cell1", "Cell2", "Cell3"]),
                         cellData(opened: false, title: "Thursday, September 13, 2018", sectionData: ["Cell1", "Cell2", "Cell3"]),
                         cellData(opened: false, title: "Friday, September 14, 2018", sectionData: ["Cell1", "Cell2", "Cell3"])]
    }

    override func numberOfSections(in tableView: UITableView) -> Int
    {
        return tableViewData.count
    }
    
//
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        if tableViewData[section].opened == true
        {
            return tableViewData[section].sectionData.count + 1
        }
        else
        {
            return 1
        }
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
     let dataIndex = indexPath.row - 1
        
     if indexPath.row == 0
     {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else {return UITableViewCell()}
        cell.textLabel?.text = tableViewData[indexPath.section].title
        
        return cell
     }
        

     else
     {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else {return UITableViewCell()}
        cell.textLabel?.text = tableViewData[indexPath.section].sectionData[dataIndex]
        
        return cell
     }
    }
//
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        if tableViewData[indexPath.section].opened == true
        {
            tableViewData[indexPath.section].opened = false
            let sections = IndexSet.init(integer: indexPath.section)
            tableView.reloadSections(sections, with: .none)// play around with this
        }
        
        else
        {
            tableViewData[indexPath.section].opened = true
            let sections = IndexSet.init(integer: indexPath.section)
            tableView.reloadSections(sections, with: .none)// play around with this
        }
    }

//

}

Swift 4: структурированный массив для отображения в виде таблицы

Сборка iPhoneX: отображение разделов в виде таблицы

Сборка iPhoneX: отображение разделов и ячеек в табличном представлении при нажатии

1 Ответ

0 голосов
/ 15 сентября 2018

Это самый простой способ, который я могу придумать.Вам понадобятся две дополнительные переменные - одна для get ting count, другая для добавленного заголовка count.Если вы не против создать строку для отображения самостоятельно, вы можете пропустить вторую.

struct cellData {
    var opened = Bool()
    var title = String()
    var sectionData = [String]()

    var count: Int {
        get {
            return sectionData.count
        }
    }
    // This variable is for convenience
    var titleWithCount: String {
        get {
            return "\(title) (\(count) Cells)" // Format it as you require
        }
    }
}

Использовать переменную titleWithCount при заполнении заголовка раздела.

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