Macos 在swift中以编程方式清除NSView
我有一个连接到自定义类的Macos 在swift中以编程方式清除NSView,macos,cocoa,swift,drawing,nsview,Macos,Cocoa,Swift,Drawing,Nsview,我有一个连接到自定义类的NSView。该视图上有一些图形: class LineDrawer: NSView { var linear = NSBezierPath() var storage = NSUserDefaults.standardUserDefaults() override func drawRect(dirtyRect: NSRect) { var color = NSColor() if let newLoadedD
NSView
。该视图上有一些图形:
class LineDrawer: NSView {
var linear = NSBezierPath()
var storage = NSUserDefaults.standardUserDefaults()
override func drawRect(dirtyRect: NSRect) {
var color = NSColor()
if let newLoadedData = storage.objectForKey("color") as? NSData {
if let currentColor = NSUnarchiver.unarchiveObjectWithData(newLoadedData) as? NSColor {
color = currentColor
}
}
color.set()
linear.lineWidth = CGFloat(storage.integerForKey("width"))
linear.stroke()
}
override func mouseDown(theEvent: NSEvent) {
super.mouseDown(theEvent)
let location = theEvent.locationInWindow
var lastPt = theEvent.locationInWindow
lastPt.y -= frame.origin.y
linear.moveToPoint(lastPt)
}
override func mouseDragged(theEvent: NSEvent) {
super.mouseDragged(theEvent)
var newPt = theEvent.locationInWindow
newPt.y -= frame.origin.y
linear.lineToPoint(newPt)
needsDisplay = true
}
}
现在我需要编写一个函数来完全清除这个视图 不太清楚你所说的完全清晰的视图是什么意思,但你不能用纯色填充它吗
[[NSColor windowBackgroundColor] setFill];
NSRectFill(self.bounds);
(还没赶上火热的速度)
更新
看,我的排骨真快
NSColor.windowBackgroundColor().setFill()
NSRectFill(self.bounds)
像这样的东西就足够了。我在我的项目中使用了类似的方法来清除NSView
while curView.subviews.count > 0 {
curView.subviews.last?.removeFromSuperview()
}
Swift 4.2解决方案:
myView.subviews.removeAll()
谢谢,我正在寻找一种删除图形的方法,但这也会很好。是的,一旦应用了图形,就不能删除它。另一种方法是在类上设置一个标志,打开或关闭特定图形,并告诉视图
setNeedsDisplay:YES
。在下一次通过时,视图将为空白,如果不需要其他图纸,则不会进行任何绘制。这比每次绘制图形,然后使用rect fill擦除图形更有效。