2016-08-02 91 views
1

I just create a new application project   1的Xcode 7.3版(7D175)
  2.swift 2.2版
  3.Mac OS版本OS X EI Capitan的10.11.4
我想为Mac OS和 一个桌面应用程序我已经设置了窗口级别,但这不起作用。如何让窗户始终保持最快的速度?

+1

您是否在设置级别之前检查窗口是否存在(!= nil)? – larva

+0

窗口属性它可能是零。没有什么与你的语法有关。 –

+0

http://stackoverflow.com/a/35714647/2303865 –

回答

1

你需要检查窗口!=前无任何自定义代码

class ViewController: NSViewController { 
    var addedObserver = false 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     if let window = self.view.window { 
      // custom window here 
      window.level = Int(CGWindowLevelForKey(.FloatingWindowLevelKey)) 
     } else { 
      addedObserver = true 
      self.addObserver(self, forKeyPath: "view.window", options: [.New, .Initial], context: nil) 
     } 
    } 

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { 
     if let window = self.view.window { 
      // custom window here 
      window.level = Int(CGWindowLevelForKey(.FloatingWindowLevelKey)) 
     } 
    } 

    deinit { 
     if addedObserver { 
      self.removeObserver(self, forKeyPath: "view.window") 
     } 
    } 
} 
+0

谢谢。我已将您的代码添加到我的项目中,但无法将窗口保留在顶部 –

+0

@SteveJiang在//自定义窗口中进行了代码调用?我确实创建了一个新项目并尝试使用此代码。它的工作和窗口字体顶部,但我不知道什么NSWindow级别做。 – larva

+1

'NSApplication.sharedApplication()。windows.first?.level =' –

0

还在测试它,但是这是幼虫在斯威夫特4回答,它似乎是工作。

var observingFloat = false 

override func viewDidLoad() { 
     super.viewDidLoad() 
     self.view.wantsLayer = true 

     if self.view.window != nil { 
      NSApplication.shared.windows.first?.level = NSWindow.Level(rawValue: 1) 
     } else { 
      observingFloat = true 
      self.addObserver(self, forKeyPath: "view.window", options: [.new, .initial], context: nil) 
     } 
    } 

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { 

     if self.view.window != nil { 
      NSApplication.shared.windows.first?.level = NSWindow.Level(rawValue: 1) 
     } 
    } 
相关问题