我试图只复制必要的代码来显示我的问题。我有一个动态内容的桌面视图。我创建了一个原型单元格,它有一个用户名和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)
}
你需要记住你评价过哪些人。由于单元格是可重用对象,因此'dequeueReusableCellWithIdentifier'可以为不同的indexPath值返回相同的单元实例。 – ozgur
您应该拥有“RatingTableViewCell”类中的评分单元格的所有逻辑。它不属于'cellForRowAtIndexPath'函数。 – rmaddy
我有一个选定费率的数组。我在cellForRowAtIndexPath上使用它。我有一个模型是用户[indexPath.row],我用userId == model.id来查看我的ratingArr。我听说使用标签来保持当前的索引是一个坏主意。也许这就是问题所在。 –