Xamarin ios - 从动态UIAlertController获取所选项目的值时出错
问题描述:
我有一个列表,它创建了多年,并使用此列表动态创建UIAlertController。Xamarin ios - 从动态UIAlertController获取所选项目的值时出错
用户从tableview中的一行中点击一个按钮,启动UIAlertController并且用户可以选择一年。
我的挑战是:
- 每一次我选择控制器一年,它选择了取消按钮。
获取所选动作的索引的正确方法是什么?
// Create a new Alert Controller
actionSheetAlert =
UIAlertController.Create ("", "SELECT YEAR", UIAlertControllerStyle.ActionSheet);
try {
for (int i = 0; i < years.Count; i++) {
// Add Actions
actionSheetAlert.AddAction (
UIAlertAction.Create (years [i].ToString(), UIAlertActionStyle.Default,
(action) => {
string year = actionSheetAlert.Actions.ElementAt(i).ToString();
Console.WriteLine ("Selected year:" + year);
this.DismissViewController (true, null);
}
));
}
} catch (Exception ex) {
Console.WriteLine (ex.Message + ex.StackTrace);
}
actionSheetAlert.AddAction (
UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel,
(action) => {
this.DismissViewController (true, null);
}
));
this.PresentViewController (actionSheetAlert, true, null);
答
该解决方案非常简单。
只需接入选择这样的行动的Title属性:
更改此
string year = actionSheetAlert.Actions.ElementAt(i).ToString();
对此
string year = action.Title;