主要内容

uiswitch

创建滑块开关、跷板开关或拨动开关组件

说明

s = uiswitch 在新图窗中创建一个滑块开关,并返回 Switch 对象。MATLAB® 调用 uifigure 函数来创建该图窗。

s = uiswitch(parent) 在指定的父容器中创建一个开关。父容器可以是 Figure 对象或其子容器之一。

示例

s = uiswitch(style) 创建指定样式的开关。开关样式可以是 "slider""rocker""toggle"

s = uiswitch(parent,style) 在指定的父容器中创建指定样式的开关。

示例

sw = uiswitch(___,Name,Value) 支持上述语法中的任何输入参量组合,且可使用一个或多个名称-值参量指定开关属性。例如,uiswitch("FontWeight","bold") 创建一个带粗体标签文本的开关。

示例

示例

全部折叠

在 UI 图窗中创建一个滑块开关。

fig = uifigure("Position",[100 100 300 300]);
s = uiswitch(fig);

Figure contains an object of type uiswitch.

在 UI 图窗中创建一个拨动开关。

fig = uifigure("Position",[100 100 300 300]);
ts = uiswitch(fig,"toggle");

Figure contains an object of type uitoggleswitch.

创建具有一个面板的 UI 图窗。创建一个跷板开关,将该面板指定为父容器。

fig = uifigure("Position",[100 100 300 300]);
p = uipanel(fig);
rs = uiswitch(p,"rocker");

Figure contains an object of type uipanel.

在 UI 图窗中创建一个滑块开关。

fig = uifigure("Position",[100 100 300 300]);
s = uiswitch(fig);

Figure contains an object of type uiswitch.

通过设置 Items 属性来更改开关标签文本。

s.Items = ["Stop","Start"];

Figure contains an object of type uiswitch.

确定当前开关值。

val = s.Value
val = 
'Stop'

在 UI 图窗中创建一个水平拨动开关。

fig = uifigure("Position",[100 100 300 300]);
ts = uiswitch(fig,"toggle","Orientation","horizontal");

Figure contains an object of type uitoggleswitch.

创建一个 App,当用户拨动跷板开关的值时,它会改变灯的颜色。

在名为 updateLampColor.m 的文件中,编写实现该 App 的函数:

  • 创建一个 UI 图窗和网格布局管理器,以对该 App 进行布局。

  • 在网格布局管理器中创建一个灯和一个跷板开关。

  • 编写一个名为 updateLamp 的回调函数(该函数根据开关的值改变灯的颜色),并将该函数分配给开关的 ValueChangedFcn 回调属性。有关回调的详细信息,请参阅Create Callbacks for Apps Created Programmatically

function updateLampColor
fig = uifigure("Position",[100 100 150 300]);
g = uigridlayout(fig);
g.RowHeight = {'1x','fit'};
g.ColumnWidth = {'1x'};

lmp = uilamp(g);

s = uiswitch(g,"rocker");
s.Items = ["Go","Stop"];
s.ValueChangedFcn = @(src,event) updateLamp(src,event,lmp);
end

function updateLamp(src,event,lmp)
val = src.Value;
switch val
    case "Go"
        lmp.Color = "green";
    case "Stop"
        lmp.Color = "red";
end
end

运行 updateLampColor 函数。与开关交互以改变灯的颜色。

updateLampColor

Figure contains an object of type uigridlayout.

输入参数

全部折叠

父容器,指定为 Figure 对象或其子容器之一:TabPanelButtonGroupGridLayout。如果不指定父容器,MATLAB 会调用 uifigure 函数创建新 Figure 对象充当父容器。

开关的样式,指定为下表中的值:

样式外观
"slider"Slider switch, with a value of Off on the left and On on the right. The value of the switch is Off.
"rocker"Rocker switch, with a value of On at the top and Off at the bottom. The value of the switch is Off.
"toggle"Toggle switch, with a value of On at the top and Off at the bottom. The value of the switch is Off.

名称-值参数

Name1=Value1,...,NameN=ValueN 的形式指定可选参量对组,其中 Name 是参量名称,Value 是对应的值。名称-值参量必须出现在其他参量之后,但参量对组的顺序无关紧要。

示例: uiswitch(Items=["0","1"]) 将两种开关状态指定为 "0""1"

在 R2021a 之前,使用逗号分隔每个名称和值,并用引号将 Name 引起来。

示例: uiswitch("Items",["0","1"]) 将两种开关状态指定为 "0""1"

开关的每种样式支持一组不同属性。有关每种样式的属性和描述的完整列表,请参阅相关联的开关组件页。

版本历史记录

在 R2016a 中推出

全部展开

另请参阅

函数

对象

工具