首页 > 解决方案 > 循环通过按钮单击 Xamarin 上的字符串

问题描述

 private void Button_Clicked(object sender, EventArgs e)
    {

        string[] quotes = new string[3];
        quotes[0] = "1st quote";
        quotes[1] = "2nd quote";
        quotes[2] = "3rd quote";

        for (int i = 0; i < quotes.Length; i++)
        {
            label.Text = quotes[i];
        }
    }

这是我第一个使用 xamarin 的“测试”项目,我试图弄清楚如何在按钮单击时循环遍历字符串。此外,当某个“quotes[i]”存在时,它的值等于我的 XAML 文件中的 label.Text。我对何时可以使用 int vs string 感到困惑,因为这与 JS 不同。

标签: c#xamarinxamarin.forms

解决方案


这里的问题是变量不是全局的,所以当用户停止点击按钮时,他们的进度会重置。

private int currentIndex = 0;
private void Button_Clicked(object sender, EventArgs e)
        {
             string[] quotes = new string[3];
             quotes[0] = "1st quote";
             quotes[1] = "2nd quote";
             quotes[2] = "3rd quote";

             label.Text = quotes[currentIndex];
             currentIndex++;
             if (currentIndex == 3){
                currentIndex = 0
             }
        }

这个答案确保一旦用户点击了三次,它就不会像 RippStudwell 的答案那样使程序崩溃。


推荐阅读