Xcode,删除子视图
Posted
技术标签:
【中文标题】Xcode,删除子视图【英文标题】:Xcode, remove subView 【发布时间】:2018-02-07 02:26:21 【问题描述】:我有一个应用可以显示不同时间的家庭位置。我使用 Timer 每 1 秒提前一次日期,并且每年都会从 Core Data 中检索数据,并在视图上绘制一个带有 subView 的对象,覆盖地图。我无法理解的是如何在每年前进时清除子视图。欢迎提出建议。
定时器代码:
@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)
【问题讨论】:
【参考方案1】:我认为您可以将所有标记视图存储在数组中,例如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 $0.removeFromSuperView()
markerViews.removeAll()
【讨论】:
以上是关于Xcode,删除子视图的主要内容,如果未能解决你的问题,请参考以下文章
向左滑动时未剪切子视图以删除 UITableViewCell