在Swift中以编程方式添加和删除NSTextField

cbwuti44  于 2023-08-02  发布在  Swift
关注(0)|答案(1)|浏览(133)

我正在尝试在表示各种数据点的图形视图上编写文本标签(想象一下Excel中的折线图)。
我使用tableView选择一个数据集。每次选择一个新的数据集时,图形将重新绘制。
我可以使用自定义视图绘制折线图。没问题
我可以使用以下从drawRect()调用的函数绘制文本标签:

  1. func drawDataPointLabels(size: CGSize) { //size is the view.bounds
  2. var dataLabelsArray: [(NSColor, String, NSRect)] = []
  3. // graphDetails contain an array of tuples [(), (), (), ()] - this represents one graph type = eg Monthly Fees ** there will be a maximum of 12 items in the array
  4. for graphDetails in graphDetailsArray {
  5. // each dataPoint object is a tuple (graphType: columnLabel: columnColor: columnHeight: columnNumber: ) representing one dataPoint
  6. for dataPoint in graphDetails {
  7. let graphHeight = size.height / 2
  8. let graphWidth = size.width - graphOrigin.x - rightMargin
  9. let columnAndGapSize = graphWidth / 25
  10. let labelX: CGFloat = (graphOrigin.x + columnAndGapSize) + (columnAndGapSize * dataPoint.columnNumber) * 2
  11. let labelY: CGFloat = dataPoint.columnHeight * (graphHeight - topMargin - bottomMargin)
  12. // determine the location and frame for the text label to match dataPoint
  13. let textFrame = NSRect(x: labelX, y: labelY, width: 30, height: 10)
  14. let dataPointTuple = (dataPoint.columnColor, dataPoint.columnLabel, textFrame)
  15. dataLabelsArray.append(dataPointTuple)
  16. }
  17. for dataPoint in dataLabelsArray {
  18. let (color, label, frameRect) = dataPoint
  19. let lblDataPoint = NSTextField(frame: frameRect)
  20. lblDataPoint.stringValue = label
  21. lblDataPoint.backgroundColor = backgroundColor
  22. lblDataPoint.textColor = color
  23. self.addSubview(lblDataPoint)
  24. }
  25. }
  26. }

字符串
但是,我不知道如何在视图更新和呈现新数据集时删除数据标签。图形将重新绘制,但文本标签仍保留以前的数据集。

n53p2ov0

n53p2ov01#

在函数的顶部添加以下代码已经解决了这个问题。

  1. let subViewsToRemove = self.subviews
  2. for object in subViewsToRemove {
  3. object.removeFromSuperview()
  4. }

字符串

相关问题