简体   繁体   English

Swift - 表格视图中的单元格出现在另一个单元格上

[英]Swift - Cell in tableview appear over another cell

I am making a simple tableview.我正在制作一个简单的表格视图。

The problem I am facing is that when I scroll down and back up, another cell has appeared over the cells.我面临的问题是,当我向下滚动并向上滚动时,另一个单元格出现在单元格上。

Look on the 2 images bellow.看看下面的2张图片。

在此处输入图片说明

Here you see the cell is appeared on the top, and the counter is not zero as the first cell should be.在这里,您会看到单元格出现在顶部,并且计数器不是第一个单元格应该为零。 You can also see the color has a darker color.您还可以看到颜色较深。 在此处输入图片说明

Here is the code:这是代码:

 override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
 return 200
 }

 override func numberOfSections(in tableView: UITableView) -> Int {

 return 1
 }

 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

 return 10
 }


 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) //as! ArrangementCell


 let card = CardHighlight(frame: CGRect(x: cell.bounds.origin.x + 30, y: cell.bounds.origin.y + 10, width: cell.bounds.width - 60 , height: (cell.bounds.width + 40)/2.6282051282))
 card.backgroundColor = UIColor(red: 0, green: 94/255, blue: 112/255, alpha: 0.1)
 card.title = String(Counter)
 card.hasParallax = true
 card.shadowOpacity = 0.6
 card.shadowBlur = 7
 card.cardRadius = 7


 Counter = Counter + 1

 let cardContentVC = storyboard!.instantiateViewController(withIdentifier: "CardContent") as! DetaljertArrangement
 card.shouldPresent(cardContentVC, from: self, fullscreen: false)

 cell.contentView.addSubview(card)


 return cell
 }

How can i prevent this problem?我怎样才能防止这个问题?

Because of cell dequeuing this因为单元格出列这个

cell.contentView.addSubview(card)

keeps adding a new label every scroll , so you need to create a prototype cell / xib with label hooked as outlet and change it's text每次滚动都会不断添加一个新标签,因此您需要创建一个原型单元格/xib,其标签挂钩为出口并更改其文本

It looks like your problem is this line cell.contentView.addSubview(card) .看起来您的问题是这一行cell.contentView.addSubview(card) You are adding a new content view over the old one without removing the old one.您在旧的内容视图上添加了新的内容视图,而没有删除旧的内容视图。 You could try making a UITavleViewCell subclass that has CardHighlight already added and you just update it's title and VC.您可以尝试创建一个已添加 CardHighlight 的 UITavleViewCell 子类,您只需更新它的标题和 VC。

DequeueCellAtIndexPath recycles old cells (it only creates new cells initially) so as you scroll you are using the old already set up cells. DequeueCellAtIndexPath 回收旧单元格(它最初只创建新单元格),因此当您滚动时,您正在使用旧的已经设置的单元格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM