Swift 3 / Xcode 8.3.3
当我点击屏幕时,图像在点击位置出现(代码1)(如果我点击5次,出现5个图像),每个图像都有一个标记。现在我想在每次点击按钮(代码2)时逐个删除图像,但只删除最后一张图像......
我做了很多研究,但结果都没有。
代码1:
var imageView : UIImageView!
var lstTagImage: [Int] = []
var concatenateInt: String = ""
var lstPoint: [Point] = []
concatenateInt = "\(Int(i))\(Int(j))"
lstPoint.append(Point(x: i, y: j, weigth: weigthChip))
imageView = UIImageView(frame:CGRect(x: X,
y: Y,
width: 20, height: 20));
imageView.tag = Int(concatenateInt)!
lstTagImage.append(Int(concatenateInt)!)
imageView.image = UIImage(named: imageString)
self.view.addSubview(imageView)
代码2:
@IBAction func undoButton(_ sender: UIButton) {
if (lstPoint.count != 0){
lstPoint.remove(at: lstPoint.count - 1)
imageView.removeFromSuperview()
} else {
print("list empty")
}
}
答案 0 :(得分:2)
另一种更优雅的方法是这样的:
let addedImages = [UIImageView]()
// When adding an image to the view
addedImages.append(imageView)
self.view.addSubview(imageView)
然后很容易删除。
// When deleting image from view
if let imageView = addedImages.last {
imageView.removeFromSuperview()
addedImages.removeLast()
}
答案 1 :(得分:0)
您应该使用>>> items = [[255, 204, 204], [255, 179, 179], [['250, 250, 250'], ['220, 220, 220']]]
>>> list(flatten(items))
[[255, 204, 204], [255, 179, 179], ['250, 250, 250'], ['220, 220, 220']]
来检索最后一个标记,从数组中删除该标记并从其超级视图中删除该图像。
viewWithTag