我有一张疼痛贴图,我使用位置坐标来绘制疼痛的位置。我可以添加"点"在for循环中它们显示很好。但是,在我在for循环之外实例化它们之前,我无法删除它们。因此,每次我更新视图时,它都会绘制新视图而不是旧视图。我该怎么办?
这个版本很好地添加了点,但我无法将它们移除,因为我无法调用dot.removeFromSuperview()
DispatchQueue.global(qos: .background).async {
if let locationNotNilX = self.painDiagramAnalysisModel.painLocationXFor(days: self.daysChosen){
x = locationNotNilX
count = locationNotNilX.count
}
if let locationNotNilY = self.painDiagramAnalysisModel.painLocationYFor(days: self.daysChosen){
y = locationNotNilY
}
let locationsArray = zip(x, y)
print("zipped array \(locationsArray)")
DispatchQueue.main.async {
let dot = UIImageView()
dot.removeFromSuperview()
dot.image = nil
for item in locationsArray {
self.locationPainY = (diagramHeight * CGFloat(item.1)) + originY
self.locationPainX = (diagramWidth * CGFloat(item.0)) + originX
print(" locationX \(self.locationPainX) locationY \(self.locationPainY)")
dot.image = UIImage(named: "dot")
dot.frame = CGRect(x: self.locationPainX - (dotDiameter / 4), y: self.locationPainY - (dotDiameter / 4), width: dotDiameter , height: dotDiameter)
if count > 2 {
dot.alpha = 0.6
} else {
dot.alpha = 1.0
}
dot.readingsPressedAnimation()
self.view.addSubview(dot)
}
}
}
此版本删除了点,但只有一个点(自我挂在点上,只在for for循环中实例化一次。
let dot = UIImageView()
dot.removeFromSuperview()
dot.image = nil
DispatchQueue.global(qos: .background).async {
if let locationNotNilX = self.painDiagramAnalysisModel.painLocationXFor(days: self.daysChosen){
x = locationNotNilX
count = locationNotNilX.count
}
if let locationNotNilY = self.painDiagramAnalysisModel.painLocationYFor(days: self.daysChosen){
y = locationNotNilY
}
let locationsArray = zip(x, y)
print("zipped array \(locationsArray)")
DispatchQueue.main.async {
for item in locationsArray {
self.locationPainY = (diagramHeight * CGFloat(item.1)) + originY
self.locationPainX = (diagramWidth * CGFloat(item.0)) + originX
print(" locationX \(self.locationPainX) locationY \(self.locationPainY)")
dot.image = UIImage(named: "dot")
dot.frame = CGRect(x: self.locationPainX - (dotDiameter / 4), y: self.locationPainY - (dotDiameter / 4), width: dotDiameter , height: dotDiameter)
if count > 2 {
dot.alpha = 0.6
} else {
dot.alpha = 1.0
}
dot.readingsPressedAnimation()
self.view.addSubview(dot)
}
}
}
如何添加点的多个实例并将其移除到循环外?
答案 0 :(得分:6)
迭代您的地图子视图并移除所有UIImageViews
:
func removeDots() {
for case let dot as UIImageView in yourPainMapView.subViews {
dot.removeFromSuperView()
}
}
如果您使用的是其他UIImageView
子视图,则不希望删除子类UIImageView
(class MyDot:UIImage {...}
):
for case let dot as MyDot in yourPainMapView.subViews