Skip to main content

Window

toggle-button

See the ToggleButtonDemo.cs.

using Gridrand.RimGui.Manual.Utility;

namespace Gridrand.RimGui.Manual
{
/// <summary>
/// <see cref="Gui.ToggleButton(ref bool, int)"/>
/// <see cref="Gui.BeginToggleButton(bool, int)"/> demo.
/// </summary>
class ToggleButtonDemo : ManualBase, IManual
{
bool isSelected1 = true;
bool isSelected2 = true;
bool isSelected3 = true;

int tabCount = 3;
int selectedIndex = 1;

public ToggleButtonDemo(ManualBaseResource p) : base(p)
{
}

public void Draw()
{
DrawToggleButtons();
Gui.Heading("Tab-like");
DrawTabLike();
}

void DrawToggleButtons()
{
// Basic ToggleButton usage with a direct boolean reference.
if (Gui.ToggleButton(ref isSelected1))
{
Logger.Debug("Pressed");
}

// ToggleButton using the Begin/End pattern to draw elements within the button.
using (Gui.BeginToggleButton(isSelected2))
{
Gui.Text("0");
Gui.Text("1");
Gui.Text("2");
}
// Determine whether it is selected through Context.
isSelected2 = Ctx.IsLastSelected();

Gui.ToggleButton("ToggleButton", ref isSelected3);
}

void DrawTabLike()
{
Gui.LabelSliderInputInt("Tab count", ref tabCount, 1, 10);
// Ensure the selected index is within the bounds of the tab count.
if (tabCount <= selectedIndex)
selectedIndex = 0;

// Use LayoutBuilder to create evenly distributed rectangles for the tabs.
var builder = Ctx.LayoutBuilder.Rent();
for (int i = 0; i < tabCount; i++)
builder.Fit(1f);
using var rects = builder.BuildAllocatedHorizontal();

for (int i = 0; i < tabCount; i++)
{
var isSelected = selectedIndex == i;
if (Gui.NextRect(rects[i]).ToggleButton($"{i}", ref isSelected))
{
// If the toggle button is pressed and becomes selected,
// update the selectedIndex to the current tab's index.
if (isSelected)
selectedIndex = i;
}
}

// Display the currently selected tab index in a large, centered text.
using (Style.FontSizes.Begin(50f))
using (Style.Text.AlignmentXs.Begin(Contracts.AlignmentX.Center))
Gui.NextHeight(100).Text(selectedIndex.ToString());
}
}
}