关于UITableView
有一个奇怪的问题。我有3个数据源,它意味着UITableView
中的3个部分。当我滚动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只创建了足够多的单元格,就像屏幕上可见一样,一旦单元格滚出视图,它就会被重新用于dataSource中的另一个项目。
按钮看似消失的原因是您之前已经删除了按钮,但现在,重用时没有告诉单元格再次显示按钮。
修复此问题很简单,只需添加:
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的重用。