Sky Watch

Sky Watch

马上订阅 Sky Watch RSS 更新: https://darksair.org/blog/feed.xml

IBDesignable is not enough

2018年8月1日 18:04

I was writing a macOS app in Swift, and I needed several text fields accompanied by those little stepper buttons, like what’s shown below. So I decided to write my own control which wraps the text field and the stepper together.

A bunch of steppers
Figure 1. A bunch of NSStepper’s

The custom control itself was simple enough. It was pretty much just a class containing an NSTextField with a formatter and an NSStepper, and that was it (I added a label later).

@IBDesignable
class NumberStepper: NSControl
{
    private var Text: NSTextField = NSTextField(string: "0")
    private var Stepper: NSStepper = NSStepper()
    // ...

    func initSubControls()
    {
        addSubview(Text)
        addSubview(Stepper)
        // Add constraints and stuff...
    }

    override init(frame frameRect: NSRect)
    {
        super.init(frame: frameRect)
        initSubControls()
    }

    required init?(coder: NSCoder)
    {
        super.init(coder: coder)
        initSubControls()
    }

    override func draw(_ dirtyRect: NSRect)
    {
        super.draw(dirtyRect)
    }
}

Notice I added an @IBDesignable before the class defintion. This was to say that the interface builder in Xcode should draw this control when I add it to my UI, so that it should show what’s in the control (the text field and the stepper), instead of just a grey box with “custom NSView” written on it. This was not the first time...

剩余内容已隐藏

查看完整文章以阅读更多