2016-04-27 39 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與您的費率數據綁定(可能是?)。這樣做的最好方法是你應該不會在你的視圖控制器中編寫配置單元數據和單元邏輯的代碼。如果你的業務邏輯很複雜,你會發現它是一場噩夢。^ =^

相關問題