Добавить раздел после 7 ячеек, созданных в TableView - Swift - PullRequest
0 голосов
/ 17 мая 2019

У меня есть 2 массива, один из которых содержит разделы, а другой содержит элементы для заполнения ячеек моего TableView.

Вопрос: возможно ли создать несколько разделов с заголовком после 7 ячеек?

Например, массив содержит 14 элементов, а массив массивов состоит из 2 элементов. Я хотел бы, чтобы в начале появилось «Раздел 1», затем сначала 7 элементов, затем «Раздел 2», а затем остальные элементы.

Спасибо!

 import UIKit

    class ChallengesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

        @IBOutlet weak var tableView: UITableView!

        var titleArray = [""]
        var weekSection = ["1","2"]

        override func viewDidLoad() {
            super.viewDidLoad()


>      let url = URL(string:"https://website.com/file.txt")!
>         URLCache.shared.removeAllCachedResponses()
>         let task = URLSession.shared.dataTask(with:url) { (data, response, error) in
>             if error != nil {
>                 print(error!)
>             }
>             else {
>                 if let textFile = String(data: data!, encoding: .utf8) {
>                     DispatchQueue.main.async {
>                     self.titleArray = textFile.components(separatedBy: "\n")
>                     self.tableView.reloadData()
>                     print(self.titleArray)
>                     }
>                 }
>             }
>         }
>         task.resume()

        }

         func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return titleArray.count
        }

        func numberOfSectionsInTableView(tableView: UITableView) -> Int {
            return weekSection.count
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let cell = tableView.dequeueReusableCell(withIdentifier: "challengeCell", for: indexPath) as! ChallengeTableViewCell
            cell.labelTitle.text = titleArray[indexPath.row]

            return cell
        }

        func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

            switch (section) {
            case 0:
                return "Case 0"
            case 1:
                return "Case 1"
            default:
                return "Default"
            }
        }

Ответы [ 2 ]

1 голос
/ 17 мая 2019

Обновите numberOfRowsInSection и cellForRowAt методы, подобные этому

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return "Case \(section)"
}
func numberOfSections(in tableView: UITableView) -> Int {
    let lastSection = titleArray.count % 7 == 0 ? 0 : 1
    return (titleArray.count/7) + lastSection
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let count = titleArray.count - (7*section)
    return min(7,count)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "challengeCell", for: indexPath) as! ChallengeTableViewCell
    let rowIndex = (indexPath.section*7)+indexPath.row
    cell.labelTitle.text = titleArray[rowIndex]
    return cell
}

enter image description here

0 голосов
/ 17 мая 2019

после редактирования вопроса, это один из лучших ответов, я думаю

extension Array {
 func chunked(into size: Int) -> [[Element]] {
     return stride(from: 0, to: count, by: size).map {
         Array(self[$0 ..< Swift.min($0 + size, count)])
     }
 }
}

использование:

@IBOutlet weak var tableView: UITableView!

    var titleArray: [[String]] = [[]]
    var sectionsCount: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string:"https://website.com/file.txt")!
        URLCache.shared.removeAllCachedResponses()
        let task = URLSession.shared.dataTask(with:url) { (data, response, error) in
            if error != nil {
                print(error!)
            }
            else {
                if let textFile = String(data: data!, encoding: .utf8) {
                    DispatchQueue.main.async {
                        let myArray = textFile.components(separatedBy: "\n")
                        self.sectionsCount = myArray.chunked(into: 7).count
                        self.tableView.reloadData()
                        print(self.titleArray)
                    }
                }
            }
        }
        task.resume()

    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return sectionsCount
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titleArray[section].count
    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "challengeCell", for: indexPath) as! ChallengeTableViewCell

        let sectionArray = titleArray[indexPath.section]
        cell.labelTitle.text = sectionArray[indexPath.row]

        return cell
    }
...