我正在将多个输入转储到 View 中。它们由 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 的“标签”字段存储某种标识符,然后读取通过从 View 获取所有输入并将它们与哈希表进行比较。
这是正确的做法吗?我在这里缺少一些简单的东西吗?你会怎样做呢?
编辑
为了更好地描述情况,页面上的 UITextField 数量是从 XML 文件中提取的,因此我不知道会有多少个 UITextField(因此不一定将它们分配给 Controller )
我需要一些类似的东西:
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"];
}
这也许是我可以在谷歌中找到的东西,但无法想出正确的搜索词,并且总是空手而归。在同一级别上,如果您可以更好地描述我的请求,请更新我的问题标题
最佳答案
我认为您实际上是关于属性数据的哈希表(NSDictionary)的最佳解决方案。在 View 对象本身中有太多语义数据确实是一个糟糕的设计决策,因为它与 View 无关。
您需要在代码中具体执行以下操作:
要设置您的 View 和属性数据:
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.
}
}
subview 上的枚举循环是我认为您在这里寻找的最重要的东西。它与在 jQuery 中使用选择器执行此操作的方式非常相似。
关于objective-c - 像在 HTML 中一样访问 UI 输入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11873875/