NSImage中的绘图处理程序-init不起作用(Swift)

时间:2014-06-21 05:03:04

标签: custom-controls swift nsimage

大家!

我想在awakeFromNib NSButton子类方法中为按钮设置图像。 在界面构建器中,我将按钮类设置为我的自定义类。当我将绘图代码放在重写drawRect方法时,绘图效果很好。

为什么绘图处理程序在此代码中不起作用

import Cocoa

@IBDesignable class PreviousTrackButton: NSButton {

    @IBInspectable var dx: CGFloat = 10
    @IBInspectable var dy: CGFloat = 10

    override func awakeFromNib() {
        super.awakeFromNib()

        var imageframe = NSInsetRect(self.bounds, dx, dy)

        let buttonImage = NSImage(size: imageframe.size, flipped: false, drawingHandler: {imageframe in

        NSGraphicsContext.saveGraphicsState()

        var fillColor = NSColor.whiteColor()

        println("000") // log does not in consol. 

        let point1 = NSPoint(x: NSMinX(imageframe), y: NSMidY(imageframe))
        let point2 = NSPoint(x: NSMidX(imageframe), y: NSMaxY(imageframe))
        let point3 = NSPoint(x: NSMidX(imageframe), y: NSMidY(imageframe))
        let point4 = NSPoint(x: NSMaxX(imageframe), y: NSMaxY(imageframe))
        let point5 = NSPoint(x: NSMaxX(imageframe), y: NSMinY(imageframe))
        let point6 = NSPoint(x: NSMidX(imageframe), y: NSMinY(imageframe))

        let path = NSBezierPath()
        path.moveToPoint(point1)
        path.lineToPoint(point2)
        path.lineToPoint(point3)
        path.lineToPoint(point4)
        path.lineToPoint(point5)
        path.lineToPoint(point3)
        path.lineToPoint(point6)
        path.lineToPoint(point1)
        path.closePath()
        fillColor.setFill()
        path.fill()

        NSGraphicsContext.restoreGraphicsState()

        return true
            })
        self.image = buttonImage
        println("buttonImage")  // buttonImage not nil and have an appropriate size

    }

}

println(“000”)日志不会出现在consol中。绘图处理程序不会调用。 我做错了什么?

1 个答案:

答案 0 :(得分:0)

Interface Builder可设计组件不会调用initawakeFromNib,而是您的代码应位于layoutSubviews中,如果您确实将其放在那里,它应该有效。