在为 GUI 编写代码时,我经常遇到这种情况,并且想知道解决这个问题的最佳实践方法。情况是这样的:
我的 GUI 上有许多相同的项目,它们具有不同的变量名称,即我有 10 个“相同”按钮,分别命名为 Button1、Button2、Button3 等...
按钮显示的文本在代码中更新,如果它们满足特定条件,我想检查它们何时更新,然后根据该条件更改文本颜色。所以对于 button1 我会写:
if (Button1.text == "true"){
Button1.textcolor = blue}
else if (Button1.text == "false"){
Button1.textcolor = red}
现在,必须为 10 个按钮中的每一个重新编写此代码似乎是多余的,将 Button1 的变量名替换为 Button2,依此类推,直到 Button10。有没有办法在循环中更改代码的“Button1”部分并保持其他所有内容相同?所以我正在寻找的一个伪代码示例是:
for (all buttons in (button1-button10)){
if (thisbutton.text == "true"){
thisbutton.textcolor = blue}
else if (thisbutton.text == "false"){
thisbutton.textcolor = red}}
我不知道如何最好地处理这种情况,并希望对此提供意见和指导。
谢谢