使用 getRectsBeingDrawn: Swift

Using getRectsBeingDrawn: with Swift

我正在尝试在 Swift 应用程序中使用 NSView 调用 getRectsBeingDrawn(_:count:),但无法理解如何解压 'return' 值 - 该方法的签名特别神秘。我通过 count 变量获得了预期的矩形数量,但我不知道如何访问数组中的矩形。 解决了同样的问题,并提出了一个解决方案,但它对我不起作用 - 我无法访问 NSRect 结构。

func decideWhatToRedraw() {

    let r1 = CGRect(x: 0, y: 0, width: 10, height: 20)
    let r2 = CGRect(x: 0, y: 100, width: 35, height: 15)

    setNeedsDisplayInRect(r1)
    setNeedsDisplayInRect(r2)
}

override func drawRect(dirtyRect: NSRect) {
    var rects: UnsafeMutablePointer<UnsafePointer<NSRect>> = UnsafeMutablePointer<UnsafePointer<NSRect>>.alloc(1)
    var count: Int = 0
    getRectsBeingDrawn(rects, count: &count)

    // count -> 2
    // But how to get the rects?
}

这就是你想要的:

var rects = UnsafePointer<NSRect>()
var count = Int()
getRectsBeingDrawn(&rects, count: &count)

for i in 0 ..< count {

    let rect = rects[i]

    // do things with 'rect' here

}

您创建两个变量 rectscount,并将引用传递给它们,因此它们会填充信息。

调用getRectsBeingDrawn后,rects指向count个矩形,可以通过下标访问,就像数组一样。

swift 3.2

            var rects: UnsafePointer<NSRect>?
            var count = Int()

            getRectsBeingDrawn(&rects, count: &count)
            for i in 0 ..< count {
                let rect = NSIntersectionRect(bounds, rects![i]);
                NSRectFillUsingOperation(rect, NSCompositeSourceOver)
            }