公认答案的Swift(4.0)版本基本相同:
let yellowView: NSView // your view that contains the point with the yellow arrow.
let yellowPoint = NSPoint(x: 100, y: 100)
let pointInWindow = yellowView.convert(yellowPoint, to: nil)
let pointOnScreen = yellowView.window?.convertToScreen(NSRect(origin: pointInWindow, size: .zero)).origin ?? .zero
let contentRect = NSRect(origin: pointOnScreen, size: NSSize(width: 32, height: 32))
let newWindow = NSWindow(contentRect: contentRect, styleMask: ...)
以下是另一种方法:
let someView: NSView // Some existing view
var rect: NSRect
rect = NSRect(x: 100, y: 100, width: 0, height: 0)
rect = someView.convert(rect, to: nil)
rect = someView.window?.convertToScreen(rect) ?? rect
rect.size = NSSize(width: 32, height: 32)
let newWindow = NSWindow(contentRect: rect, styleMask: ...)
后一种方式只是提前设置矩形。对于喜欢演练的人来说,这是一个逐个播放的游戏:
1.创建一个矩形。在视图坐标系中的所需位置初始化一个大小为零的矩形。
let someView: NSView // Some existing view
var rect = NSRect(x: 100, y: 100, width: 0, height: 0)
2。从视图转换到窗口。 通过将目标view 指定为nil,将矩形从视图坐标系转换到窗口坐标系。
rect = someView.convert(rect, to: nil)
3.从窗口转换到屏幕。 接下来,将矩形从窗口坐标系转换到屏幕坐标系。
请注意someView.window 可能是nil,因此我们使用可选链接(即window? 中的?)并回退到rect 的原始值(如果是这种情况)。 em> 这可能不是必需的,但这是一个好习惯。
rect = someView.window?.convertToScreen(rect) ?? rect
4.设置矩形的大小。 将矩形更新为新窗口所需的大小。
rect.size = NSSize(width: 32, height: 32)
5.创建窗口。 使用转换后的矩形初始化一个新窗口。
let newWindow = NSWindow(contentRect: rect, styleMask: ...)