ios - 难以在 swift 中为 tableview 附加数组数组
问题描述
我正在尝试从我拥有的一些数据中构建一个表格视图,但我遇到了一些我不理解的附加行为。
要调试我正在尝试这个,如果我说:
var sectionHeaders:[String] = ["0","1"]
var items:[[String]] = [["zero","zero","zero"],["one","one","one"]]
并在我的表格视图中显示它,我看到一个带有三行零的标题“0”,另一个带有三行“一”的标题“1”。这是可以预料的。但是,如果我尝试使用 append 构建相同的结构,我会得到奇怪的结果:
var sectionHeaders:[String] = []
var items:[[String]] = [[]]
var tempItems:[String] = []
sectionHeaders.append("0")
tempItems.append("zero")
tempItems.append("zero")
tempItems.append("zero")
items.append(tempItems)
tempItems = []
sectionHeaders.append("1")
tempItems.append("one")
tempItems.append("one")
tempItems.append("one")
items.append(tempItems)
有了这个,我得到一个带有零行(无行)的“0”部分标题,以及一个带有三行零的“1”标题。
数据似乎以某种方式被抵消
我附加的方式有问题吗?
我的数据源代表非常简单:
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionHeaders[section]
}
override func numberOfSections(in tableView: UITableView) -> Int {
return sectionHeaders.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "testCell", for: indexPath)
let text = items[indexPath.section][indexPath.row]
cell.textLabel?.text = text
return cell
}
}
解决方案
当你这样做时:
var items:[[String]] = [[]]
您将定义items
为具有一个元素的数组(括号的外部集),该元素是一个空数组:([]
括号的内部集)。
为了不得到偏移量,它应该是这样的:
var items:[[String]] = []
(只是一个空数组)
推荐阅读
- javascript - 本机 Javascript - 如果语句不起作用,则具有 else 属性
- ios - 如何使用“使用应用程序时”定位服务获取地理通知
- latex - 用于 LaTeX 的 pgf tikz 如何将 x 和 y 坐标与节点一起使用
- java - 在 Java 中分配给字符串缓冲区的内存没有被清除
- java - 将字符连接到字符串数组时获取“null”
- c++ - 如何在第一个节点线性链表c ++之后添加一个节点
- ubuntu - GtkDialog 映射没有临时父级。不鼓励这样做,Katalon Studio Linux (Beta GUI) 出现错误
- javascript - 使用 React Native 平面列表和粘性标题在行中渲染项目
- swift - 如何使用 swift 4 for mac os 应用程序提取和创建 .zip 文件?
- amazon - 我想用亚马逊支付快递方式检索送货地址