Xcode, 移除子视图

Xcode, remove subView

我有一个应用程序可以显示不同时间家庭的位置。我使用计时器每 1 秒推进一次日期,每年从核心数据中检索数据,并使用子视图在视图上绘制一个对象,覆盖地图。我无法理解的是如何在每年前进时清除子视图。非常欢迎提出建议。

定时器代码:

  @IBAction func startCount(_ sender: Any) {

        if !counting {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(counter), userInfo: nil, repeats: true)
        counting = true
    }
}

柜台代码:

  @objc func counter() -> Void {
    yearCount.text = String(countYear)
    compareYear = String(countYear)
    print(compareYear)
    drawCircles()
    countYear += 1
}

画圆代码:

  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)
    }
}     

我认为您可以将所有 markerView 存储在数组中,例如 var markerViews: [UIImageView] 然后

@objc func counter() -> Void {
    yearCount.text = String(countYear)
    compareYear = String(countYear)
    print(compareYear)

    clearExistingMarkerViews()
    drawCircles()
    countYear += 1
}

private func clearExistingMarkerViews() {
    markerViews.forEach { [=10=].removeFromSuperView() }
   markerViews.removeAll()
}