2013-03-25 72 views
0

我在使用此代碼添加UIButtons for循環按鈕:MonoTouch的添加在for循環

for (int i=0; i <12; i++) { 
    button = new UIButton(new RectangleF(xBase + i * 25,100 + i,25,25)); 
    button.SetBackgroundImage(UIImage.FromBundle ("Images/b.png"),UIControlState.Normal); 
    button.TouchUpInside += (s, e) => { 
     UIAlertView alert = new UIAlertView("",i.ToString(),null,"",null); 
     alert.Show(); 
    }; 
    this.Add (button); 
} 

的問題是,點擊按鈕時,我得到的值,是最後一個按鈕的加入。

我該如何解決這個問題?

回答

2

這可能是因爲C#中閉包變量的性質。嘗試將循環變量綁定到循環內的局部變量。您可能會發現一些相關信息here

1

您正在關閉循環變量。而C#中的循環變量是在循環之外定義的。

您可以修復你這樣的代碼

for (int i=0; i <12; i++) { 
    button = new UIButton(new RectangleF(xBase + i * 25,100 + i,25,25)); 
    button.SetBackgroundImage(UIImage.FromBundle ("Images/b.png"),UIControlState.Normal); 
    button.TouchUpInside += (s, e) => { 
     var j = i; 
     UIAlertView alert = new UIAlertView("",j.ToString(),null,"",null); 
     alert.Show(); 
    }; 
this.Add (button); 

}

希望你在一個for循環,而不是一個foreach這樣做,因爲在C# 5behaviour changed,但我不知道如果這個改變在單聲道3.0.X系列中還沒有實現。