I have an app that displays locations of families across time. I use a Timer to advance the date every 1 second, and at each year data is retrieved from Core Data and an object is drawn on the view with a subView, overlaying a map. What I cannot fathom is how to clear the subView each time the year advances. Suggestions would be most welcome.
Timer code:
@IBAction func startCount(_ sender: Any) {
if !counting {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(counter), userInfo: nil, repeats: true)
counting = true
}
}
Counter code:
@objc func counter() -> Void {
yearCount.text = String(countYear)
compareYear = String(countYear)
print(compareYear)
drawCircles()
countYear += 1
}
Draw Circles code:
func drawCircles() {
if markerView != nil {
if let markerView = view.viewWithTag(countYear-1){
markerView.removeFromSuperview()
}
}
var markers = [PlaceNames]()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "PlaceNames")
let predicate = NSPredicate(format: "year == %@", compareYear)
fetchRequest.predicate = predicate
do {
markers = try coreDataStack.context.fetch(fetchRequest) as! [PlaceNames]
print(markers.count)
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
for marker in markers {
placeEastings = marker.value(forKey: "eastings") as? Float
placeNorthings = marker.value(forKey: "northings") as? Float
print(placeEastings, placeNorthings)
if (placeEastings != nil && placeNorthings != nil) {
let tempXAxis = placeEastings
placeXAxis = (tempXAxis! - 6.0)/1.5
let tempYAxis = placeNorthings
placeYAxis = (tempYAxis! - 6.0)/1.5
print(placeXAxis, placeYAxis)
}
markerView = UIImageView(frame: CGRect(x: Double(placeXAxis), y: Double(placeYAxis), width: 12.0, height: 12.0))
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 12, height: 12))
markerImage = renderer.image { ctx in
let rectangle = CGRect(x: 0, y: 0, width: 12, height: 12)
ctx.cgContext.setFillColor(UIColor.white.cgColor)
ctx.cgContext.setStrokeColor(UIColor.black.cgColor)
ctx.cgContext.setLineWidth(1)
ctx.cgContext.addEllipse(in: rectangle)
ctx.cgContext.drawPath(using: .fillStroke)
}
markerView.tag = countYear
markerView.image = markerImage
self.view.addSubview(markerView)
}
}
I think you can store all markerViews in array like var markerViews: [UIImageView]
and then
@objc func counter() -> Void {
yearCount.text = String(countYear)
compareYear = String(countYear)
print(compareYear)
clearExistingMarkerViews()
drawCircles()
countYear += 1
}
private func clearExistingMarkerViews() {
markerViews.forEach { $0.removeFromSuperView() }
markerViews.removeAll()
}