1:创建的window设置styleMask:设置这个属性主要是为了去掉TitleBar,将窗口的边框去掉,方面接下来绘制内容,使窗体变漂亮
window?.styleMask = NSWindowStyleMask.texturedBackground,最初设置的是borderless,但是出现了窗口无法拖动问题
可以在xib、storyboard中直接进行设置,也可以代码设置
2:设置window的层级关系:window?.level = Int(CGShieldingWindowLevel())
CGShieldingWindowLevel 返回屏幕窗口的窗口级别,这个层级要高于屏保,即可以在其他程序处于使用激活状态时候始终保持在屏幕最前,这个方法调用需要在viewWillApear中调用,即需要在viewDidLoad之前调用,不然无效
到此即可实现桌面最高层级显示,程序开启期间始终可以保持屏幕最前
3:window.contentView的自定义,绘制自己想要实现的界面效果,window?.backgroundColor = NSColor.clear即可将window的窗体进行透明化,全部呈现contentView内容。
4.window窗体上有可以接受用户鼠标事件的需要进行sendEvent重写处理,例如在contentView上有button,要在鼠标在button内容区可以拖动窗体,可以点击,两个鼠标事件不阻塞,
步骤4我的实现尚有bug,鼠标跟随不是很贴,有待深究,若哪位大大有研究,请指点一二,mac开发小白的我万分感谢ing
4:
override func sendEvent(_ event: NSEvent) {
self.contentView?.viewTag = contentViewTag
let targetView = self.contentView?.hitTest(event.locationInWindow)
if event.type == NSEventType.leftMouseDown {
mouseDownLocation = NSEvent.mouseLocation()
mouseDownWindowFrame = self.frame
var keepOn = true
while keepOn {
let newEvent = self.nextEvent(matching: [.leftMouseDragged,.leftMouseUp], until: Date.distantFuture, inMode: RunLoopMode.eventTrackingRunLoopMode, dequeue: false)
switch newEvent!.type {
case NSEventType.leftMouseDragged:
// if targetView is SZView{
// super.sendEvent(event)
// break
// }else{
self.handleMove(event: newEvent!)
self.nextEvent(matching: [.leftMouseDragged,.leftMouseUp])
// }
isDrag = true
break
case NSEventType.leftMouseUp:
if (targetView is NSButton && isDrag) {
self.nextEvent(matching: [.leftMouseDragged,.leftMouseUp])
}else{
super.sendEvent(event)
}
isDrag = false
keepOn = false
break
default:
keepOn = false
}
}
}else {
super.sendEvent(event)
}
}
func handleMove(event:NSEvent) {
let point = NSEvent.mouseLocation()
let newMouseLocation:NSPoint = point
// self.convertToScreen(rect).origin
let delta = NSMakePoint(newMouseLocation.x-mouseDownLocation.x, newMouseLocation.y-mouseDownLocation.y)
var newFrame = mouseDownWindowFrame
newFrame?.origin.x += delta.x
newFrame?.origin.y += delta.y
self.setFrame(newFrame!, display: true, animate: true)
}