【问题标题】:Drawing handler in NSImage -init doesn't work (Swift)NSImage -init 中的绘图处理程序不起作用(Swift)
【发布时间】:2014-06-21 05:03:03
【问题描述】:

大家!

我想在 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") 日志没有出现在控制台中。绘图处理程序不调用。 我做错了什么?

【问题讨论】:

    标签: custom-controls swift nsimage


    【解决方案1】:

    Interface Builder Designable 组件不调用initawakeFromNib,而是你的代码应该位于layoutSubviews,如果你把它放在那里,它应该可以工作。

    【讨论】:

    • NSView 的子类没有“layoutSubviews”方法。是的,在我的情况下,实时渲染不起作用,但我现在只谈论绘图处理程序。只有这段代码不会调用。如您所见, buttonImage 实例不是 nil。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多