2017-09-09 44 views
0

我试图在ViewController中设置模态表的位置。 什么从来就走到这一步,是这样的:Swift模态表:willPositionSheet does not get called

import Cocoa 

class ViewController: NSViewController, NSWindowDelegate { 

    func window(_ window: NSWindow, willPositionSheet sheet: NSWindow, using rect: NSRect) -> NSRect { 
     print("function entered") 
    } 

    var sheetWindowController: SheetWindowController! 

    @IBAction func showSheet(_ sender:AnyObject){ 
     let windowController = SheetWindowController(windowNibName: "SheetWindowController") 
     self.sheetWindowController = windowController 
     self.sheetWindowController.delegate = self 
     self.view.window?.beginSheet(self.sheetWindowController.window!, completionHandler: nil) 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     self.view.window?.delegate = self 
    } 
} 

它正在尽可能的表显示了在窗口的顶部。但willPositionSheet方法不会被调用。任何想法缺少什么?

+0

请参阅[试图知道当一个窗口关闭在macOS基于文档的应用程序](https://stackoverflow.com/questions/44685445/trying-to-know-when-a-window-closes-in-a- MacOS的文档为基础的应用程序)。 – Willeke

回答

1

2件事。

第一:您的视图控制器viewwindow属性可能不会是nonnil直到viewDidAppear()(您可以通过调试断点来验证该窗口是否为nonnil)。所以确保委托实际上是在窗口上设置的。我还会注意到,你可能想要尝试将窗口委托绑定到窗口的控制器对象或不属于视图控制器的独立窗口委托对象。视图控制器是一个奇怪的地方放这个逻辑。

二:呈现由一个NSWindowController拥有的窗口似乎并没有得到这些回调出于某种原因(我只是路过一个标准NSWindow对象来测试和委托收到willPositionSheet调用)。不知道为什么会出现这种情况,但是我想这些窗口是如何设置的。据说,你可以尝试使用更新的(10.10)NSViewController演示API来使你的生活更轻松。我会尝试使用NSViewControllerpresentViewControllerAsSheet(_:)来呈现NSViewController

因此,在总结,你可以有这样的:

override func viewDidAppear() { 
    super.viewDidAppear() 
    self.view.window?.delegate = self 
} 

,并呈现:

let vc = SheetViewController() // Note this is a view controller, not window controller 
presentViewControllerAsSheet(vc) 

希望有点帮助。