2013-03-25 71 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系列中还没有实现。