2016-04-27 50 views
1

我试图只复制必要的代码来显示我的问题。我有一个动态内容的桌面视图。我创建了一个原型单元格,它有一个用户名和10颗星(这是一个评级页)。允许该组中的人对其他人进行评分。一切正常,但我向下滚动时遇到问题。如果我用8星评价我的第一个用户,当我向下滚动时,位于桌面视图底部区域的某位用户以我给第一位用户的费率出现。我知道tableview重用单元格。我尝试了很多东西,但没有成功。希望有人能帮助我。UITableView乱七八糟的行内容

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let model = users[indexPath.row] 

     let cell = tableView.dequeueReusableCellWithIdentifier("RatingCell") as! RatingTableViewCell 
     cell.tag = indexPath.row 

     cell.playerLabel.text = model.name 

     cell.averageView.layer.borderWidth = 1 
     cell.averageView.layer.borderColor = Color.Gray1.CGColor 
     cell.averageView.layer.cornerRadius = 5 

     cell.starsView.userInteractionEnabled = true 

     cell.averageLabel.text = "\(user.grade)" 

     for i in 0...9 { 
      let star = cell.starsView.subviews[i] as! UIImageView 
       star.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(starTap))) 
      star.userInteractionEnabled = true 
      star.tag = i 
      star.image = UIImage(named: (i + 1 <= grade ? "star-selected" : "star-empty")) 
     } 
     return cell 
} 

func changeRating(sender: UIImageView) { 
    let selectedStarIndex = sender.tag 
    let cell = sender.superview?.superview?.superview as! RatingTableViewCell 
    let model = users[cell.tag] 
    let stars = sender.superview?.subviews as! [UIImageView] 

    cell.averageLabel.text = "\(selectedStarIndex + 1)" 

    for i in 0...9 { 
     let imgName = i <= selectedStarIndex ? "star-selected" : "star-empty" 
     stars[i].image = UIImage(named: imgName) 
    } 
} 

func starTap(gesture: UITapGestureRecognizer) { 
    changeRating(gesture.view as! UIImageView) 
} 
+1

你需要记住你评价过哪些人。由于单元格是可重用对象,因此'dequeueReusableCellWithIdentifier'可以为不同的indexPath值返回相同的单元实例。 – ozgur

+0

您应该拥有“RatingTableViewCell”类中的评分单元格的所有逻辑。它不属于'cellForRowAtIndexPath'函数。 – rmaddy

+0

我有一个选定费率的数组。我在cellForRowAtIndexPath上使用它。我有一个模型是用户[indexPath.row],我用userId == model.id来查看我的ratingArr。我听说使用标签来保持当前的索引是一个坏主意。也许这就是问题所在。 –

回答

1

解决此问题的方法是更新包含uitableviewcell的所有信息的模型。每当评级更新为特定单元格时,请确保您在数组中的相应对象/字典中反映该更新。而且,如果你有一个customuitableviewcell,那么重置“prepareForUse”函数中的星星可能是一个好主意,这样当一个单元被重用时它不会使用旧数据。

0

在你的评论中,你说你有一个选择率的数组,但你并没有在你的代码中显示。

在我看来,你需要记录indexPath也因为indexPath.row与您的费率数据绑定(可能是?)。这样做的最好方法是你应该不会在你的视图控制器中编写配置单元数据和单元逻辑的代码。如果你的业务逻辑很复杂,你会发现它是一场噩梦。^ =^