2017-10-15 39 views
0

我有自定義表格視圖單元格有評級星星。我使用https://github.com/hsousa/HCSStarRatingView進行評分查看。 有我的表視圖和單元格視圖的代碼。當滾動表格視圖內容更改

class RatingTableViewCell: UITableViewCell { 

     var value : CGFloat = 0.0 
     @IBOutlet weak var starRatingView: HCSStarRatingView! 
     @IBOutlet weak var titleLabel: UILabel! 
     override func awakeFromNib() { 
      super.awakeFromNib() 
      initStarRatingView() 
      starRatingView.addTarget(self, action: #selector(DidChangeValue(_:)), for: .valueChanged) 

     } 

     override func setSelected(_ selected: Bool, animated: Bool) { 
      super.setSelected(selected, animated: animated) 

      // Configure the view for the selected state 
     } 

     private func initStarRatingView() { 
     var scalingTransform : CGAffineTransform! 
     scalingTransform = CGAffineTransform(scaleX: -1, y: 1); 
     starRatingView.transform = scalingTransform 
     starRatingView.emptyStarImage = #imageLiteral(resourceName: "strokStar") 
     starRatingView.halfStarImage = #imageLiteral(resourceName: "halfStar") 
     starRatingView.filledStarImage = #imageLiteral(resourceName: "fillStar") 
     starRatingView.allowsHalfStars = true 
     } 


     @IBAction func DidChangeValue(_ sender: HCSStarRatingView) { 

     self.value = sender.value 
     } 

class RatingViewController: CustomViewController,UITableViewDelegate,UITableViewDataSource { 

    var values : [CGFloat] = [0.5,0.0,0.0,0.0,0.0,0.0,0.0] 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCell(withIdentifier: "RatingTableViewCell", for: indexPath) as! RatingTableViewCell 

    values[indexPath.row] = cell.value 
    cell.starRatingView.value = values[indexPath.row] 
    return cell 
    } 
//MARK: _Table data source 

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

    values.count 
    } 

} 

當我滾動表格視圖時出現問題。可重複使用的單元格數據出錯是錯誤的。如何更新每個單元格的值數據?

回答

1

問題是你正在存儲單元格中的值。看看這兩條線:

let cell = tableView.dequeueReusableCell(withIdentifier: "RatingTableViewCell", for: indexPath) as! RatingTableViewCell 
values[indexPath.row] = cell.value 

你出列單元格,並指定它的值值[indexPath.row。您在滾動時注意到的問題是由於重複使用的單元格以前用於不同的indexPath,這意味着它們的值(您分配給值[indexPath.row])是針對其之前的indexPath。

要解決這個問題,我會建議擺脫RatingTableViewCell中的值變量。相反,定義一個協議RatingTableViewCellDelegate將用於通知RatingViewController有關新值。

+0

我defice協議中的TableCell類協議RatingTableViewCellDelegate { FUNC setCellRating(單元:RatingTableViewCell) } – ava

+0

和呼叫委託方法:覆蓋FUNC awakeFromNib(){ super.awakeFromNib() initStarRatingView() starRatingView.addTarget(自我,動作:#selector(DidChangeValue(_ :)),用於:.valueChanged) 如果讓委託= {self.delegate delegate.setCellRating(細胞:個體經營) }} 委託 – ava

+0

條件不叫 – ava