在SWIFT OS X中以编程方式添加和删除NSTextField
问题描述:
我正在尝试在代表各种数据点的图形视图(想象Excel中的线图)上编写文本标签。在SWIFT OS X中以编程方式添加和删除NSTextField
我使用tableView选择一个数据集。每次选择一个新的数据集时,图形都会重新绘制。
我可以使用自定义视图绘制线条图。没问题。
我可以使用)从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)
}
}
}
但是,我不能工作,如何当视图更新删除数据标签和一个新的数据集呈现。图形重新绘制,但文本标签仍然来自先前的数据集。
任何指导/建议,将不胜感激。
答
将下面的代码添加到函数的顶部已经解决了我的问题。
let subViewsToRemove = self.subviews
for object in subViewsToRemove {
object.removeFromSuperview()
}