UITableView
有一个奇怪的问题。我有 3 个数据源,这意味着 3 个部分在UITableView
.当我滚动UITableView
时,按钮和图像是冲突的。按钮消失,图像变形。
这是我cellForRowAt
方法。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "eventnetworkingcell", for: indexPath) as! EventNetworkCell
var name: String = ""
var job: String = ""
var company: String = ""
var img: Int?
cell.userImageView.layer.cornerRadius = 45
cell.userImageView.clipsToBounds = true
if indexPath.section == 0 {
name = self.matchmaking[indexPath.row].name
job = self.matchmaking[indexPath.row].job
company = self.matchmaking[indexPath.row].company
img = self.matchmaking[indexPath.row].image
}
else if indexPath.section == 1 {
name = self.networkInEvent[indexPath.row].name
job = self.networkInEvent[indexPath.row].job
company = self.networkInEvent[indexPath.row].company
img = self.networkInEvent[indexPath.row].image
cell.addButtonOutlet.alpha = 0
}
else {
name = self.allAttendees[indexPath.row].name
job = self.allAttendees[indexPath.row].job
company = self.allAttendees[indexPath.row].company
img = self.allAttendees[indexPath.row].image
}
cell.nameLabel.text = name
cell.jobLabel.text = job
cell.companyLabel.text = company
if let imgid = img {
let url = MTApi.url(for: imgid, size: .normal)
cell.userImageView.sd_setImage(with: url, placeholderImage: nil, options: [], completed: nil)
}
}
cell.addButtonOutlet.addTarget(self, action:
#selector(self.addNetwork(sender:)), for: .touchUpInside)
return cell
}
当我删除cell.addButtonOutlet.alpha = 0
行时,按钮不会消失。
并且有一个视频显示了该问题:
视频
您在重复使用单元格时遇到问题。
基本上,正在发生的事情是,tableView 只创建屏幕上可见的足够多的单元格,一旦单元格滚动到视图之外,它就会被重新用于数据源中的另一个项目。
按钮似乎消失的原因是您之前已经删除了该按钮,但现在,在重用时没有告诉单元格再次显示该按钮。
解决此问题很容易,只需添加:
cell.addButtonOutlet.alpha = 0
到您的第 0 和第 2 部分(否则阻止(。
与图像相同,除非您告诉单元格在需要时删除图像,否则将保留以前的图像,因此只需添加以下内容:
if let imgid = img {
let url = MTApi.url(for: imgid, size: .normal)
cell.userImageView.sd_setImage(with: url, placeholderImage: nil, options: [], completed: nil)
} else {
cell.userImageView.image = nil
}
var name: String = ""
var job: String = ""
var company: String = ""
var img: Int?
cell.userImageView.layer.cornerRadius = 45
cell.userImageView.clipsToBounds = true
cell.addButtonOutlet.alpha = 1 // add more
if indexPath.section == 0 {
........
你应该研究UITableviewCell重用。