在 SWIFT OS X 中以编程方式添加和删除 NSTextField

Adding and removing NSTextField programatically in SWIFT OS X

我正在尝试在表示各种数据点的图表视图上写文本标签(想象 Excel 中的折线图)。

我select一个数据集使用了tableView。每次 select 一个新的数据集都会重新绘制图形。

我可以使用自定义视图绘制折线图。没问题。

我可以使用从 drawRect() 调用的以下函数绘制文本标签:

func drawDataPointLabels(size: CGSize) {  //size is the view.bounds

    var dataLabelsArray: [(NSColor, String, NSRect)] = []

    // 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
    for graphDetails in graphDetailsArray {

         // each dataPoint object is a tuple (graphType:  columnLabel: columnColor:  columnHeight:  columnNumber: ) representing one dataPoint
        for dataPoint in graphDetails {
            let graphHeight = size.height / 2
            let graphWidth = size.width - graphOrigin.x - rightMargin
            let columnAndGapSize = graphWidth / 25
            let labelX: CGFloat = (graphOrigin.x + columnAndGapSize) + (columnAndGapSize * dataPoint.columnNumber) * 2
            let labelY: CGFloat = dataPoint.columnHeight * (graphHeight - topMargin - bottomMargin)

            // determine the location and frame for the text label to match dataPoint
            let textFrame = NSRect(x: labelX, y: labelY, width: 30, height: 10)
            let dataPointTuple = (dataPoint.columnColor, dataPoint.columnLabel, textFrame)
            dataLabelsArray.append(dataPointTuple)
        }

        for dataPoint in dataLabelsArray {
            let (color, label, frameRect) = dataPoint
            let lblDataPoint = NSTextField(frame: frameRect)
            lblDataPoint.stringValue = label
            lblDataPoint.backgroundColor = backgroundColor
            lblDataPoint.textColor = color
            self.addSubview(lblDataPoint)
        }
    }
}

但是,我不知道如何在更新视图和显示新数据集时删除数据标签。图表重新绘制,但文本标签仍然来自以前的数据集。

任何 guidance/suggestions 将不胜感激。

将以下代码添加到函数的顶部已经解决了我的问题。

        let subViewsToRemove = self.subviews

        for object in subViewsToRemove {
            object.removeFromSuperview()
        }