Macos 如何在Swift语言中更改NSView的角半径
更改NSView的角半径应该非常简单,但我收到错误消息“致命错误:无法展开可选。无”。有没有可能我是用10.9而不是10.10来做这件事的,并且这是由于框架的不同而发生的?或者代码是错误的Macos 如何在Swift语言中更改NSView的角半径,macos,cocoa,nsview,swift,Macos,Cocoa,Nsview,Swift,更改NSView的角半径应该非常简单,但我收到错误消息“致命错误:无法展开可选。无”。有没有可能我是用10.9而不是10.10来做这件事的,并且这是由于框架的不同而发生的?或者代码是错误的 class aRoundView: NSView { let cornerRad = 5.0 init(frame: NSRect) { super.init(frame: frame) self.layer.cornerRadius = cornerR
class aRoundView: NSView {
let cornerRad = 5.0
init(frame: NSRect) {
super.init(frame: frame)
self.layer.cornerRadius = cornerRad
}
override func drawRect(dirtyRect: NSRect)
{
super.drawRect(dirtyRect)
NSColor.redColor().setFill()
NSRectFill(dirtyRect)
}
}
编辑
打电话进来
func applicationDidFinishLaunching(aNotification: NSNotification?) {
let aView = mainViewTest(frame: NSMakeRect(0, 0, 100, 100))
self.window.contentView.addSubview(aView)
}
事实并非如此。使用self.layer的任何迭代都会给出相同的结果、背景色等。这是因为
self.layer
是一个可选值,当前未设置该值。在self.layer.cornerRadius
之前添加self.wantsLayer=true
,以确保存在正确的层
init(frame: NSRect) {
super.init(frame: frame)
self.wantsLayer = true
self.layer.cornerRadius = cornerRad
}
具体是哪个呼叫导致了错误?您能确定导致错误的线路吗?我把你的代码粘贴到操场上,它没有给我任何错误。它将是self.layer
,在初始化中是nil
。它是一个分层视图吗?在调用之前,请尝试self.wantsLayer=true
。