【问题标题】:Struct and array to populate sections of Tableview in SWIFT用于在 SWIFT 中填充 Tableview 部分的结构和数组
【发布时间】:2016-03-01 04:24:28
【问题描述】:

我有一个定义帖子的结构 (getItems) 当我阅读我的帖子时,我将它们存储在一个数组中:

var posts = [getItems]()

问题是: 我决定在我的表格视图中创建部分 如何创建帖子数组? 我试图声明var items = [posts](),但这不起作用

我还有一个项目计数器,用于计算每个部分应该有多少项目,但我不知道如何将我的 getItems 数组拆分为类似的内容:

[index1 : [getItems1, getItems2 ...], index2:[getItems1, getItems2 ...]...]

这样我就可以在我的 TableView 中调用部分和行

真诚的 PS:我没有发布任何代码,因为这里有很多数据......

【问题讨论】:

  • 你的问题太模糊了。是否只想根据计数器将posts 拆分为多个子数组?
  • 是的,我需要将它们分段

标签: arrays swift uitableview struct sections


【解决方案1】:

抱歉浪费了您的时间,很简单,我在尝试声明数组数组时弄错了

不得不做

data = [[getitems]]()

【讨论】:

  • 天哪,这很方便,我犯了同样的错误。
【解决方案2】:

我不完全确定这是否是您想要的。假设您有一个 counter 函数,该函数将部分索引作为参数并返回该特定部分中应该有多少帖子。

func counter(index: Int) -> Int {
    return index
}

然后像这样计算你的子数组:

var currentIndex = 0
var totalCount = 0
var sections: [Int: [getitems]] = [:]
while totalCount < posts.count {
    let currentCounter = counter(currentIndex)
    sections[currentIndex] = posts.suffixFrom(totalCount).prefix(currentCounter).flatMap { $0 }
    currentIndex++
    totalCount += currentCounter
}

然后在你的func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    • 2017-07-22
    • 2016-06-29
    • 1970-01-01
    • 2015-06-17
    • 2016-09-14
    • 1970-01-01
    相关资源
    最近更新 更多