0

我将多个输入转储到一个视图中。它们由 UITextFields、UIPickerViews 和 UIDatePickers 组成。

他们每个人都有一个ID和一个Key,在保存输入值时需要保存。因此,当单击“保存”按钮时,我需要循环并存储以下内容:

{
   ID: 'inputid',
   Key: 'yearly',
   Value: (UITextField value)
}

在 HTML 中,我只需将这些值添加到输入 ( <input type="text" id="inputid" name="yearly" />) 中,然后使用 $(input).attr('id') 等循环遍历每个值。

在Objective-C中,我能想到的唯一方法是在绘制输入时保留此信息的哈希表,然后针对UITextField的“标签”字段存储某种标识符,然后通过获取来自视图的所有输入并将它们与哈希表进行比较。

这是正确的方法吗?我在这里错过了一些简单的东西吗?你会怎么做?

编辑
为了更好地描述情况,页面上的 UITextFields 的数量是从 XML 文件中提取的,因此我不知道会有多少 UITextFields(所以不能将它们分配给控制器)

我需要一些类似的东西:

foreach(var question in ArrayOfQuestions) {
    UITextField *textField = [[UITextField alloc] initWithFrame:];
    textField.attributes["id"] = question.Id;
    textField.attributes["key"] = question.Key;
}

并在保存方法中

foreach(var textField in UIView) {
    textField = (UITextField)textField;
    NSString *id = textField.attributes["id"];
    NSString *key = textField.attributes["key"];
}



这也许是我可以在谷歌中找到的东西,但想不出正确的搜索词并且空手而归。在同一级别,如果您能更好地描述我的要求,请更新我的问题的标题

4

2 回答 2

1

关于属性数据的哈希表(NSDictionary),我认为您实际上是最佳解决方案。在视图对象本身中包含过多的语义数据确实是一个糟糕的设计决策,因为它与视图无关。

您需要在代码中具体执行以下操作:

要设置您的视图和属性数据:

UIView *containerView; // The view that contains your UITextViews.
NSMutableDictionary *attributes; // A dictionary mapping tags to questions.
NSMutableArray *arrayOfQuestions; // The questions that you've parsed from a file or whatever.

// ...

// Each "question" would be of the form @{ @"id" : ____, @"key" : ____ }
for (NSDictionary *question in arrayOfQuestions) {
    UITextField *textField = [[[UITextField alloc] initWithFrame:aFrame] autorelease];
    [containerView addSubview:textField];
    textField.tag = getATag(); // However you want to tag them.

    // Fancy new objective-C container/object-literal syntax :)
    attributes[@(textField.tag)] = question;
}

然后对于您的“保存”方法:

for (UIView *childView in containerView.subviews) {
    if ([childView isKindOfClass:[UITextView class]]) {
        // We know the class and can thus safely typecast the UIView.
        UITextField *textField = (UITextField *)childView;

        NSDictionary *aQuestion = attributes[@(textView.tag)];

        // Now you can access the id and key properties of the question.

        // ... Whatever else you want to do.
    }
}

子视图上的枚举循环是我认为你在这里寻找的大事。这与在 jQuery 中使用选择器执行此操作的方式非常相似。

于 2012-08-09T02:58:33.017 回答
0

如果将每个元素都设为视图控制器的属性,则可以从任何地方直接访问它们并获取当前值。

因此在附加到保存按钮的方法中,您可以像这样获取 UITextField 的当前字符串值,例如:

NSString *currentTextFieldString = self.someTextField.text;
于 2012-08-08T22:59:12.340 回答