IBDesignable is not enough
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.
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...
剩余内容已隐藏
IBDesignable is not enough
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.
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...
剩余内容已隐藏