2017-10-15 15 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

問題は、セルに値を格納していることです。その2つの行を見てみましょう:

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

セルをデキューし、その値を値[indexPath.row]に割り当てます。再スクロールされたセルが以前は別のindexPathに使用されていたことが原因でスクロール時に気付いていた問題は、その値(値[indexPath.row]に割り当てる)は以前のindexPathを意味します。

これを修正するには、RatingTableViewCellのvalue変数を削除することをおすすめします。代わりに、RatingViewControllerに新しい値を通知するために使用されるプロトコルRatingTableViewCellDelegateを定義します。

+0

iは、のTableCellクラスプロトコルRatingTableViewCellDelegate { FUNCのsetCellRating(セル:RatingTableViewCell) }でプロトコルをdefice – ava

+0

とデリゲートメソッドを呼び出す:オーバーライドをawakeFromNib(){ super.awakeFromNib() initStarRatingView() starRatingView.addTarget(機能セルフ、アクション:#selector(DidChangeValue(_ :))について:.valueChanged) せデリゲート= self.delegateなら{ delegate.setCellRating(セル:自己) }} – ava

+0

デリゲート条件 – ava

関連する問題