swift 正确的方法子类化NSWindow

k10s72fa  于 2023-06-28  发布在  Swift
关注(0)|答案(1)|浏览(121)

我正在尝试添加一个这样的NSWindow:

customWindow = NSWindow.init(contentRect: rect, styleMask: styleMask, backing: NSBackingStoreType.Buffered, defer: false)
customWindow?.backgroundColor = NSColor(calibratedHue: 0, saturation: 1.0, brightness: 0, alpha: 0.3)
customWindow?.ignoresMouseEvents = true
customWindow?.level = Int(CGWindowLevelForKey(.MaximumWindowLevelKey))
customWindow?.makeKeyAndOrderFront(customWindow)

它显示了它应该的样子,但我想把它子类化。

class Screen: NSWindow {

    init() {
        let screen = NSScreen.mainScreen()
        let frame = NSMakeRect(0, 0, (screen?.frame.size.width)!, (screen?.frame.size.height)!)
        let styleMask = NSBorderlessWindowMask
        let rect = NSWindow.contentRectForFrameRect(frame, styleMask: styleMask)

        super.init(contentRect: rect, styleMask: styleMask, backing: .Buffered, defer: false)

        self.styleMask = styleMask
        self.backingType = NSBackingStoreType.Buffered
        self.setFrame(rect, display: true)  
        self.backgroundColor = NSColor(calibratedHue: 0.5, saturation: 1.0, brightness: 0, alpha: 0.6)
        self.ignoresMouseEvents = true
        self.level =  Int(CGWindowLevelForKey(.MaximumWindowLevelKey))

    }
}

我试着这样补充:

let win = Screen()
win.makeKeyAndOrderFront(win)

我是新来的,花了半天的时间寻找它是如何做的,没有运气..

ktecyv1j

ktecyv1j1#

在Swift 5中,这将是可行的:

class Screen: NSWindow {

    override init(contentRect: NSRect, styleMask style: NSWindow.StyleMask, backing backingStoreType: NSWindow.BackingStoreType, defer flag: Bool) {  
        let screen      = NSScreen.main
        let frame       = NSMakeRect(0, 0, (screen?.frame.size.width/2)!, (screen?.frame.size.height/2)!) //...using half the screen size
        let styleMask   = NSWindow.StyleMask.defaultWindow
        let rect = NSWindow.contentRect(forFrameRect: frame, styleMask: styleMask)

        super.init(contentRect: rect, styleMask: styleMask, backing: .buffered, defer: false)

        self.styleMask          = styleMask
        self.backingType        = NSWindow.BackingStoreType.buffered
        self.setFrame(rect, display: true)
        self.backgroundColor    = NSColor(calibratedHue: 0.5, saturation: 1.0, brightness: 0, alpha: 0.6)
        self.ignoresMouseEvents = false // ...to be able to click on window
        self.level              = .normal
    } 
}

为了显示窗口:

let myScreenWindow = Screen()
    let myWindowController = NSWindowController(window: myScreenWindow)
    myWindowController.showWindow(myScreenWindow)

干杯

相关问题