How to change Corner Radius of NSView in Swift Language

限于喜欢 提交于 2019-12-24 02:31:51

问题


changing corner radius of NSView should be pretty straight forward however i am getting error message "fatal error: Can't unwrap Optional.None". is there a chance i am doing this with 10.9 not 10.10 and this is happening due framework differences? or the code is wrong.

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)
    }
}

EDIT

calling it in

func applicationDidFinishLaunching(aNotification: NSNotification?) {

    let aView = mainViewTest(frame: NSMakeRect(0, 0, 100, 100))
    self.window.contentView.addSubview(aView)

}

actually it is not just that. any iteration with self.layer gives same result, backgroundcolor etc.


回答1:


That is because self.layer is an Optnional value, which is currently not set. Add self.wantsLayer = true before self.layer.cornerRadius, to make sure a proper layer exists.

init(frame: NSRect) {
    super.init(frame: frame)
    self.wantsLayer = true
    self.layer.cornerRadius  = cornerRad
}


来源:https://stackoverflow.com/questions/24038964/how-to-change-corner-radius-of-nsview-in-swift-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!