我已经使用 PLIST 实现了一个 tableView 来设置属性。
我想在特定行添加三个部分。 (第 12 行、第 24 行、第 35 行)
我已经尝试使用以下代码,但是代码太多而且效果不佳。
下面添加了图片和代码。
import UIKit
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tblStoryList: UITableView!
var array = PLIST.shared.mainArray
var array = PLIST.shared.mainArray
let sections: [String] = ["First stage","Second Stage","Third Stage"]
let s1Data : [String] = ["Row1","Row2","Row3"]
let s2Data : [String] = ["Row4","Row5","Row6"]
let s3Data : [String] = ["Row7","Row8","Row9"]
var sectionData: [Int: [String]] = [:]
override func viewDidLoad() {
super.viewDidLoad()
sectionData = [0: s1Data, 1: s2Data, 2: s3Data]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (sectionData[section]?.count)!
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "StoryTableviewCell", for: indexPath) as! StoryTableviewCell
//making plist file
let dict = self.array[indexPath.row]
let title = dict["title"] as! String
let imageName = dict["image"] as! String
let temp = dict["phrases"] as! [String:Any]
let arr = temp["array"] as! [[String:Any]]
let detail = "progress \(arr.count)/\(arr.count)"
//property to plist file
cell.imgIcon.image = UIImage.init(named: imageName)
cell.lblTitle.text = title
cell.lblSubtitle.text = detail
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
}
最佳答案
您在 tableView 的 cellForRowAt 中获取的 indexPath.row 是相对于该部分的。您不能直接将它用作主数组(包含所有行)的索引。
您需要执行一个简单的计算来将 indexPath.row 转换为该数组的索引(通过用前面部分的总项目数偏移该行):
let index = [0,12,36][indexPath.section] + indexPath.row
let dict = array[index]
同样的事情也适用于您对 numberOfRowsInSection 的响应:
return [12,24,35][section]
我觉得有点奇怪的是数据结构 (PLIST) 会如此严格以至于它总是包含那些数量的条目并且永远不会改变。如果只是为了避免到处散布硬编码数字(例如 12、24、35、36),我建议采用更通用的方法。
例如:
// declare section attributes in your class
let sectionTitles = ["First stage","Second Stage","Third Stage"]
let sectionSizes = [12,24,35] // central definition, easier to maintain (or adjust to the data)
let sectionOffsets = sectionSizes.reduce([0]){$0 + [$0.last!+$1] }
// and use them to respond to the table view delegate ...
let index = sectionOffsets[indexPath.section] + indexPath.row
let dict = array[index]
// ...
return sectionSizes[section] // numberOfRowsInSection
使用这种方法,您不需要创建 sectionData(除非您在其他地方将其用于其他目的)。
顺便说一句,在您的示例代码中,sectionData 内容是用与预期的部分大小不一致的数据硬编码的,因此即使使用正确的索引计算也无法正常工作。
关于ios - 在特定单元格添加一个部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44275778/