Native NSSwitch gadget

Mac OSX specific forum
mrbungle
Enthusiast
Enthusiast
Posts: 149
Joined: Wed Dec 30, 2020 3:18 am

Native NSSwitch gadget

Post by mrbungle »

Code: Select all


#NSControlStateValueOff = 0
#NSControlStateValueOn  = 1

Global switch1

Procedure CreateSwitch(x, y, win)
	Define rect.NSRect
	rect\origin\x = x
	rect\origin\y = y
	rect\size\width  = 51
	rect\size\height = 31
	
	Protected sw = CocoaMessage(0, 0, "NSSwitch alloc")
	sw = CocoaMessage(0, sw, "initWithFrame:@", @rect)
	CocoaMessage(0, sw, "setEnabled:", #YES)
	CocoaMessage(0, sw, "setState:", #NSControlStateValueOff)
	
	Protected contentView = CocoaMessage(0, WindowID(win), "contentView")
	CocoaMessage(0, contentView, "addSubview:", sw)
	
	ProcedureReturn sw
EndProcedure


If OpenWindow(0, 200, 200, 300, 200, "NSSwitch", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
	
	switch1 = CreateSwitch(20, 80, 0)
	
	lastState = CocoaMessage(0, switch1, "state")
	
	Repeat
		Select WaitWindowEvent()
			Case #PB_Event_CloseWindow
				Break
		EndSelect
		
		currentState = CocoaMessage(0, switch1, "state")
		If currentState <> lastState
			Debug "Switch toggled state = " + Str(currentState)
			lastState = currentState
		EndIf
		
	ForEver
EndIf