Send value in callback

1 次查看(过去 30 天)
Tim Reddering
Tim Reddering 2022-6-2
Hi,
I want to have a Switch1 to change Text1 and Switch2 to change Text2 etc. I came up with the following code:
% function to change the text
function ChangeText(value, number)
switch value
case 'On'
app.(['Text' number]).Value = 'Hi';
case 'Off'
app.(['Text' number]).Value = 'Bye';
end
end
% callback for switch 1
function Switch1ValueChanged(app, event)
value = app.Switch1.Value;
app.ChangeText(value, '1')
end
% callback for switch 2
function Switch2ValueChanged(app, event)
value = app.Switch2.Value
app.ChangeText(value, '2')
end
This way the lines of code is reduced because the ChangeTex function is not in every callback. Still I would like to have less code. Is it possible to have one callback with the code of the ChangeText function, that can be called by all the switches and change the text paired with the switch? So one callback that causes a switch in switch n to change text n.
Already thankfull for the reply!

回答(1 个)

Walter Roberson
Walter Roberson 2022-6-2
https://www.mathworks.com/help/matlab/creating_guis/write-callbacks-for-gui-in-app-designer.html#mw_54ae4804-091b-4168-a240-3defb0bc2ceb shows how to share callbacks.
I recommend that you follow the section immediately after that to create your own callback. Custom callbacks accept app, src, and event. src will be the handle to the object that triggered the callback. You can have stored information within the object, such UserData, which could be the name of the field that should be updated.
  2 个评论
Tim Reddering
Tim Reddering 2022-6-2
Can you maybe help me with an example for the case I described above? I do not understand how to work with the custom callbacks. Can I use the src (handle) to find the switch name? Or how do I use the handle?
Walter Roberson
Walter Roberson 2022-6-2
function SwitchValueChanged(app, src, event)
value = src.Value;
app.ChangeText(value, src.UserData)
end
Having set app.Switch1.UserData to '1', app.Switch2.UserData to '2' and so on

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Maintain or Transition figure-Based Apps 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by