我实例化一个UIAlertController并将UIDatePicker分配给它的一个UITextField作为输入视图。我还为选择器分配了一个ValueChanged事件处理程序。 UIDatePicker正确显示提到的UITextField何时获得焦点,但是当我更改应用程序崩溃的日期值时。
请考虑以下代码。
var d = UIAlertController.Create( "Confirm", "Fill below with the required info.", UIAlertControllerStyle.Alert);
d.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, ((UIAlertAction obj) => SubmitAction(obj, d))));
d.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null));
d.AddTextField((delegate(UITextField obj) {
UIDatePicker picker = new UIDatePicker ();
picker.ValueChanged += (object sender, EventArgs e) => { obj.Text = picker.Date.Description; };
obj.InputView = picker;
}));
PresentViewController(d, true, null);
再次,选择器显示罚款。即使使用EMPTY处理程序picker.ValueChanged += (object sender, EventArgs e) => {};
,应用程序也会在ValueChanged事件中崩溃。
没有添加事件处理程序就没有崩溃!
此代码位于按钮TouchUpInside事件处理程序中。
我在哪里做错了?
答案 0 :(得分:1)
我认为您在代码示例中混淆了事件方法。 TouchUpInside
不会为拣货员开火。如果要在选择新日期值时更新文本视图的内容,则需要使用:
picker.ValueChanged += (pickerSender, pickerArgs) =>
{
obj.Text = picker.Date.Description;
};
为防止崩溃,您需要保留对UIDatePicker实例的引用,否则将过早收集。最简单的方法是将日期选择器移动到类范围:
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Perform any additional setup after loading the view, typically from a nib.
this.btnTest.TouchUpInside += HandleTouchUpInside;
}
UIDatePicker picker;
void HandleTouchUpInside (object sender, EventArgs e)
{
var d = UIAlertController.Create( "Confirm", "Fill below with the required info.", UIAlertControllerStyle.Alert);
d.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, ((UIAlertAction obj) => {})));
d.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null));
d.AddTextField((delegate(UITextField obj) {
picker = new UIDatePicker ();
picker.ValueChanged += (pickerSender, pickerArgs) =>
{
obj.Text = picker.Date.Description;
};
obj.InputView = picker;
}));
PresentViewController(d, true, null);
}