当滚动表格视图内容更改
问题描述:
我有自定义表格视图单元格有评级星星。我使用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
}
}
当我滚动表格视图时出现问题。可重复使用的单元格数据出错是错误的。如何更新每个单元格的值数据?
答
问题是你正在存储单元格中的值。看看这两条线:
let cell = tableView.dequeueReusableCell(withIdentifier: "RatingTableViewCell", for: indexPath) as! RatingTableViewCell
values[indexPath.row] = cell.value
你出列单元格,并指定它的值值[indexPath.row。您在滚动时注意到的问题是由于重复使用的单元格以前用于不同的indexPath,这意味着它们的值(您分配给值[indexPath.row])是针对其之前的indexPath。
要解决这个问题,我会建议摆脱RatingTableViewCell中的值变量。相反,定义一个协议RatingTableViewCellDelegate将用于通知RatingViewController有关新值。
我defice协议中的TableCell类协议RatingTableViewCellDelegate { FUNC setCellRating(单元:RatingTableViewCell) } – ava
和呼叫委托方法:覆盖FUNC awakeFromNib(){ super.awakeFromNib() initStarRatingView() starRatingView.addTarget(自我,动作:#selector(DidChangeValue(_ :)),用于:.valueChanged) 如果让委托= {self.delegate delegate.setCellRating(细胞:个体经营) }} 委托 – ava
条件不叫 – ava