因为当您滚动UITableView时,单元格被重用,所以每个重用的单元格的渐变色都会发生变化。
初始化渐变颜色数组
let primaryGradientColorsArray = [Color1,Color2,Color3];
let secondaryGradientColorsArray = [Color1,Color2,Color3];
在UITableView中
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AllOfferlistCell
cell.lbltitle.text = "Index \(indexPath.row)"
if self.DataArray[indexPath.row].Flag == "1"{
cell.VwPercentage.layer.insertSublayer(gradient(frame: cell.VwPercentage.bounds, colors: [primaryGradientColorsArray[indexPath.row],secondaryGradientColorsArray[indexPath.row]]), at: 1)
cell.lblPopular.text = "POPULAR"
}else{
cell.VwPercentage.layer.insertSublayer(gradient(frame: cell.VwPercentage.bounds, colors: [primaryGradientColorsArray[indexPath.row],secondaryGradientColorsArray[indexPath.row]]), at: 1)
cell.lblPopular.text = "50% OFF"
}
return cell
}