gpt4 book ai didi

arrays - 如何使用 swift 用两个不同的数组填充 TableView 中的两个部分?

转载 作者:IT王子 更新时间:2023-10-29 05:04:37 28 4
gpt4 key购买 nike

我有两个数组 Data1 和 Data2,我想将每个数组中的数据(它们包含字符串)填充到两个不同部分的 TableView 中。

第一部分的标题应为“Some Data 1”,第二部分的标题应为“KickAss”。

我的两个部分都填充了第一个数组中的数据(但也没有标题)。

到目前为止,这是我的代码:

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

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rowCount = 0
if section == 0 {
rowCount = Data1.count
}
if section == 1 {
rowCount = Data2.count
}
return rowCount
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let ip = indexPath
cell.textLabel?.text = Data1[ip.row] as String
return cell
}

在 cellForRowAtIndexPath 方法中,我是否可以像在 numberOfRowsInSection 方法中那样以某种方式识别该部分?

另外,如何给每个部分命名?

最佳答案

TableView 单元格

您可以使用多维数组。例如:

let data = [["0,0", "0,1", "0,2"], ["1,0", "1,1", "1,2"]]

对于节数,使用:

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

然后,要指定每个部分中的行数,请使用:

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

最后,您需要设置您的单元格:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellText = data[indexPath.section][indexPath.row]

// Now do whatever you were going to do with the title.
}

TableView 标题

您可以再次使用数组,但这次只有一维:

let headerTitles = ["Some Data 1", "KickAss"]

现在为各节设置标题:

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section < headerTitles.count {
return headerTitles[section]
}

return nil
}

上面的代码检查该部分是否有标题并返回它,否则返回nil。如果 headerTitles 中的标题数量小于 data 中的数组数量,则不会有标题。

结果

enter image description here

关于arrays - 如何使用 swift 用两个不同的数组填充 TableView 中的两个部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29578965/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com