我正在构建一个应用程序,其中我在 UITableView 中有几个部分。我目前的解决方案是将我的数据收集在字典中,然后为每个部分选择一个键。有更好的解决方案吗?
最佳答案
其中一个好方法 - 直接模型映射,尤其适用于快速枚举。 例如,您有 2 个不同的部分,其中包含 3 种不同类型的行。您的枚举和 ViewController 代码将如下所示:
enum TableViewSectionTypes {
case SectionOne
case SectionTwo
}
enum TableViewRowTypes {
case RawTypeOne
case RawTypeTwo
case RawTypeThreeWithAssociatedModel(ModelForRowTypeNumberThree)
}
struct ModelForRowTypeNumberThree {
let paramOne: String
let paramTwo: UIImage
let paramThree: String
let paramFour: NSData
}
struct TableViewSection {
let type: TableViewSectionTypes
let raws: [TableViewRowTypes]
}
class ViewController: UIViewController, UITableViewDataSource {
var sections = [TableViewSection]()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].raws.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let raw = sections[indexPath.section].raws[indexPath.row]
switch raw {
case .RawTypeOne:
// Here return cell of first type
case .RawTypeTwo:
// There return cell of second type
case .RawTypeThreeWithAssociatedModel(let modelForRawTypeThree):
// And finally here you can use your model and bind it to your cell and return it
}
}
}
有什么好处?强大的类型化、显式建模和对各种单元格类型的显式处理。在这种情况下,您唯一需要做的简单事情就是将您的数据解析为枚举和结构,就像您为字典所做的那样。
关于ios - 在 UITableView 的部分中填充行的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39143920/