【问题标题】:Add section after 7 cell created in TableView - Swift在 TableView 中创建的 7 个单元格后添加部分 - Swift
【发布时间】:2019-05-17 07:32:48
【问题描述】:

我有 2 个数组,一个包含部分,另一个包含用于填充 TableView 单元格的元素。

问题是:是否可以在 7 个单元格之后创建多个带有标题的部分?

例如,数组包含 14 个元素,section 数组包含 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"
            }
        }

【问题讨论】:

  • Show.Your.Code.
  • 问题已更新

标签: swift tableview sections


【解决方案1】:

像这样更新numberOfRowsInSectioncellForRowAt 方法

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
}

【讨论】:

  • “编译器无法在合理的时间内对该表达式进行类型检查;尝试将表达式分解为不同的子表达式”以了解 numberOfSectionsInTableView 的情况
  • 仍然,只显示第一行和 7 个元素。所以它缺少第 2 节和其他 7 个元素
  • 计数中的 14 个元素
【解决方案2】:

在编辑问题后,这是我认为最好的答案之一

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
    }

【讨论】:

  • 但是如何在 TableView 中组织它们以显示部分?
  • 太棒了!如果我动态管理数组?意思是我通过我的服务器更新它?
  • 请解释清楚
  • 基本上我的数组一开始是空的。然后我正在阅读一个在线文本文件,并用元素填充它并重新加载 TableView。
  • 在您的请求末尾或在您的完成块内(如果有的话)只需输入一个tableView.reloadData();也许那时,因为你不确定你的 titleArray 有 7 个或更多你可以检查的元素,在拆分之前,if titleArray.count &gt; 7 否则你会得到一个致命错误,因为索引超出范围
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多