我通过cellForRowAt
方法以编程方式创建了ImageView,并且还添加到了单元格中:
let imageName = "Default.png"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 29, y: 17, width: 14, height: 13)
cell.addSubview(imageView)
它有效,没有任何抱怨。现在,我只想在indexpath.row等于2时显示此图像,因此我添加了一个简单的if语句:
if indexPath.row == 2 {
let imageName = "Default.png"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 29, y: 17, width: 14, height: 13)
cell.addSubview(imageView)
}
有效。但是当我向下滚动时,某些单元格也有图像。我怀疑cellForRowAt
中存在问题,因此我在UITableViewCell
中添加了prepareForReuse
方法来隐藏每个imageView,并且只有在if语句为true时,隐藏才会被删除:
override func prepareForReuse() {
super.prepareForReuse()
self.imageView!.isHidden = true
}
if indexPath.row == 2 {
let imageName = "Default.png"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 29, y: 17, width: 14, height: 13)
imageView.isHidden = false
cell.addSubview(imageView)
}
不幸的是,它不起作用,我也不知道我可以改善什么。
答案 0 :(得分:1)
prepareForReuse
引用了子类的属性imageView
并将其设置为隐藏。但是,在您的if
语句中,您正在创建一个新的图像视图并将其添加到单元格的层次结构中。这是一个坏主意,因为它将永远不会被删除,并且随着您的滚动浏览,它将越来越多地被添加。
相反,请引用单元格的图像视图:
if indexPath.row == 2 {
let imageName = "Default.png"
let image = UIImage(named: imageName)
cell.imageView?.image = image
cell.imageView?.isHidden = false
}
答案 1 :(得分:0)
在cellForRowAt
中为else部分添加空白的imageView来解决此问题。
if indexPath.row == 2 {
let imageName = "Default.png"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 29, y: 17, width: 14, height: 13)
cell.addSubview(imageView)
} else { // ## Add this else methode.
let imageView = UIImageView()
imageView.frame = CGRect(x: 29, y: 17, width: 14, height: 13)
cell.addSubview(imageView)
}
答案 2 :(得分:0)
您的代码的问题是,当单元被重用时,imageView仍在层次结构中,因此在prepareForReuse中删除图像视图类型的子视图也仅仅是因为该单元已经具有默认imageview,所以创建一个新的imageView类并删除该特定类型,我为此添加了代码,希望对您有所帮助:)。
class CustomImageView : UIImageView { //CustomImageView
}
func removeCustomImageViewIfNeeded() {
self.subviews.forEach { (subView) in
if subView is CustomImageView {
subView.removeFromSuperview()
}
}
}
override func prepareForReuse() {
super.prepareForReuse()
removeCustomImageViewIfNeeded()
}
if indexPath.row == 2 {
let imageName = "Default.png"
let image = UIImage(named: imageName)
let imageView = CustomImageView(image: image!)
imageView.frame = CGRect(x: 29, y: 17, width: 14, height: 13)
imageView.isHidden = false
cell.addSubview(imageView)
}else {
removeCustomImageViewIfNeeded()
}