![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/176844/image.png)
How can I force a slider UIcontrol object in GUIDE to move in discrete steps?
20 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
MathWorks Support Team
am 11 Mai 2015
Bearbeitet: MathWorks Support Team
am 5 Sep. 2018
I would like to create a slider UIcontrol object that moves only to integer values between a range of 1 and 16. By default, the slider can be dragged to non-integer values. How can I force the slider to move to only integer values?
Akzeptierte Antwort
MathWorks Support Team
am 5 Sep. 2018
Bearbeitet: MathWorks Support Team
am 5 Sep. 2018
In order to create a slider UIcontrol object that moves to only integer values, we would need to ensure that 1) clicking the arrow keys and 2) dragging the slider, both move the slider to an integer position. The following illustrate how to do this:
1) Clicking the arrow keys
In order to ensure that clicking the arrow keys moves slider one unit, we can set the minimum step size of the slider to be 1/(MaxSliderValue-MinSliderValue). In this particular example, you would set it as 1/15 units. This can be set by using the 'SliderStep' property of the slider object. In the example code, we have set the 'SliderStep' to [1/15 1]. This means that clicking on the left or right arrow would move the slider 1/15 normalized units (or 1 integer value) and clicking the space between the slider and the arrows would move it completely to one side (this is set by the second element of 'SliderStep', which is equal to 1 in this example).
2) Dragging the slider
In order to ensure that dragging the slider moves it to an integer position, we can round off the value pointed by the slider in the callback function, and also set the position of the slider to this rounded off value.
The following example code illustrates this:
function myslider
figure;
sld = uicontrol('Style', 'slider',...
'Min',1,'Max',16,'Value',8,...
'Units', 'Normalized',...
'Position', [0.3 0.48 0.4 0.04],...
'Callback', @print_val,...
'SliderStep', [1/15 1]);
end
function print_val(hObject,callbackdata)
newval = hObject.Value; %get value from the slider
newval = round(newval); %round off this value
set(hObject, 'Value', newval); %set slider position to rounded off value
disp(['Slider moved to ' num2str(newval)]); %display the value pointed by slider
end
This screenshot shows the generated GUI and the output at the command line after playing around with the slider for a while:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/176844/image.png)
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Migrate GUIDE Apps finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!