【发布时间】:2020-09-25 03:49:34
【问题描述】:
我正在尝试将部分添加到我的 UITableView。我能够创建部分并正确计算每个部分中的元素数量,单元格/图像与所有部分中的数据重复。
只发布相关代码:
型号:
struct Product:Equatable {
let imagename: UIImage
}
var productarray = [
Product(imagename:#imageLiteral(resourceName: "blue")),
Product( imagename:#imageLiteral(resourceName: "CakeImage")),Product(imagename:#imageLiteral(resourceName: "vectorlogo")),
Product(imagename:#imageLiteral(resourceName: "PeasImge")),Product(imagename:#imageLiteral(resourceName: "castle")),
Product( imagename:#imageLiteral(resourceName: "scoobydoo")),Product(imagename:#imageLiteral(resourceName: "ufo")),
Product( imagename:#imageLiteral(resourceName: "wolfsky")),Product( imagename:#imageLiteral(resourceName: "universe")),
Product(imagename:#imageLiteral(resourceName: "werewolf")),Product( imagename:#imageLiteral(resourceName: "galaxy"))
]
视图控制器:
class ProductViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let sections = ["Section A", "Section B","Section C", "Section D","Section E"]
let rowspersection = [2,3,2,2,2]
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rowspersection[section]
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let data = productarray[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "ProductTableViewCell") as! ProductTableViewCell
cell.imageView?.image = data.imagename
cell.myParent = self
return cell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch(section) {
case 0: return "Section A"
case 1: return "Section B"
case 2: return "Section C"
case 3: return "Section D"
case 4: return "Section E"
default: return ""
}
}
}
结果是:
说明:
“struct Product”模型中“productarray”中的图片是:
blue, CakeImage, vectorlogo, PeasImge, castle, scoobydoo , ufo, wolfsky, universe, werewolf, galaxy
但模拟器中的最终产品是:
A 部分:蓝色,CakeImage
B 部分:蓝色、CakeImage、vectorlogo
C 部分:蓝色,CakeImage
D 部分:蓝色,CakeImage
E 部分:蓝色,CakeImage
即图像/单元格在重复,我不想发生这种情况。我希望将这些部分放置在我希望的单元格/图像之间。请帮助我。
我想要的是:-
A 部分:蓝色,CakeImage
B 部分:vectorlogo、PeasImge、城堡
C 部分:史酷比、不明飞行物、
D部分:狼斯基,宇宙
E区:狼人,银河
注意:我不想更改模型“struct Product”,因为那样我将不得不更改我在这里没有提到的其他扩展代码。
【问题讨论】:
-
我不明白你想要什么,你不希望每个部分都重复前面的项目但继续显示上一个项目?
-
@ItayBrenner - 请参阅编辑
-
问题出在主题:...没有改变模型。这样做,而不是硬编码
numberOfRows和numberOfSections创建一个合适的模型。 -
更换型号。