根据以下代码,我第一次运行应用程序。 前3行正常工作。 但是当我向上和向下滚动时。 有些线也会改变。 当我多做一点上下 它改为其他行
我该如何解决这个问题
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = KategoriEkleCell()
var KategoriId :String = ""
if tableView == tableView {
cell.selectionStyle = .none
cell = self.tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath as IndexPath) as! KategoriEkleCell
cell.itemLabel.text = (AltKategoriKayit[indexPath.section][indexPath.row] as? [String:String])?["kategoriadi"]
cell.itemLabel.font = UIFont(name:"OpenSans-Light", size: 14.0)
KategoriId = ((AltKategoriKayit[indexPath.section][indexPath.row] as? [String:String])?["kategoriid"])!
if (KategoriId) == (MenuKategoriKayit[indexPath.row]["kategoriid"]!) {
cell.EkleButton.layer.cornerRadius = 2
cell.EkleButton.layer.borderWidth = 1
cell.EkleButton.layer.borderColor = UIColor(red: 255/255, green: 56/255, blue: 107/255, alpha: 1.0).cgColor
cell.EkleButton.backgroundColor = UIColor(red: 255/255, green: 56/255, blue: 107/255, alpha: 1.0)
cell.EkleButton.setTitleColor(UIColor.white, for: .normal)
cell.EkleButton.clipsToBounds = true
}else {
cell.EkleButton.layer.cornerRadius = 2
cell.EkleButton.layer.borderWidth = 1
cell.EkleButton.layer.borderColor = UIColor(red: 255/255, green: 56/255, blue: 107/255, alpha: 1.0).cgColor
cell.EkleButton.clipsToBounds = true
}
}
return cell
}
答案 0 :(得分:1)
正如评论中所提到的,细胞被重复使用。
您必须确保在cellForRow
中将任何UI元素设置为已定义的状态。我将if
和else
分支中执行的重复行移出if - else
范围,以提高可读性。
顺便说一句,if行中的括号也不需要
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let specialRed = UIColor(red: 1.0, green: 56/255, blue: 107/255, alpha: 1.0)
let cell = self.tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath) as! KategoriEkleCell
cell.selectionStyle = .none
cell.itemLabel.text = (AltKategoriKayit[indexPath.section][indexPath.row] as? [String:String])?["kategoriadi"]
cell.itemLabel.font = UIFont(name:"OpenSans-Light", size: 14.0)
let KategoriId = ((AltKategoriKayit[indexPath.section][indexPath.row] as? [String:String])?["kategoriid"])!
cell.EkleButton.layer.cornerRadius = 2
cell.EkleButton.layer.borderWidth = 1
cell.EkleButton.clipsToBounds = true
cell.EkleButton.layer.borderColor = specialRed.cgColor
if KategoriId == MenuKategoriKayit[indexPath.row]["kategoriid"]! {
cell.EkleButton.backgroundColor = specialRed
cell.EkleButton.setTitleColor(UIColor.white, for: .normal)
} else {
cell.EkleButton.backgroundColor = UIColor.white
cell.EkleButton.setTitleColor(specialRed, for: .normal)
}
return cell
}
请注意,根据命名约定,变量名称应以小写字母开头。