在Xamarin.iOS中选择并验证多个TextField

时间:2014-04-01 08:55:54

标签: ios validation uitextfield xamarin

我有多个从Json文件生成的TextField到TableViewController中。 TextFields都有99作为Tag。我有一个RightBarButton,当按下该按钮时,Console应显示TextFields中的值,但只显示最后一个TextField的值。

如何验证它们,以便检查所有TextField是否都包含数据?

这是我的RightBarButton:

NavigationItem.SetRightBarButtonItem (
    new UIBarButtonItem(UIBarButtonSystemItem.Save, ((sender, e) => {
        ValidateEditFields();
    }))
, true);

这是ValidateEditFields():

public virtual void ValidateEditFields(){
    Console.WriteLine("{0}", TextField.Text);
}

这就是我将TextField添加到TableCells的方法:

public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
    {

        if (elements [indexPath.Row].Type == "textField") {

            EditField element = elements [indexPath.Row] as EditField;

            NSString FieldID = new NSString ("EditField");

            UITableViewCell cell = tableView.DequeueReusableCell (FieldID);
            cell.SelectionStyle = UITableViewCellSelectionStyle.None;

            var setTextField = cell.ViewWithTag (99) as UITextField;

            if (setTextField == null) {
                TextField = new UITextField ();
                TextField.Placeholder = element.Placeholder;
                TextField.Tag = 99;
                TextField.SecureTextEntry = element.Secure;

                cell.AddSubview (TextField);

                EditFieldProperties ();
            }

            cell.TextLabel.Text = element.Label;
            cell.DetailTextLabel.Hidden = true;

            return cell;
        } 
    }

1 个答案:

答案 0 :(得分:1)

我通过添加一个新的UITextField列表来修复它:

public List<UITextField> TextFieldList = new List<UITextField>();

将它们添加到GetCell方法的列表中,如下所示:

if (setTextField == null) {
    TextField = new UITextField ();

    TextFieldList.Add(TextField);        

    cell.AddSubview (TextField);
}

ValidateEditFields

中循环播放这些内容
foreach (UITextField item in TextFieldList) {
    if (item.Text == "") {
        item.BackgroundColor = UIColor.Red;
    } else {
         Console.WriteLine (item.Text);
    }
}