【发布时间】:2012-06-28 09:42:37
【问题描述】:
我正在尝试编写数据驱动应用程序,在其中解析 json 字符串以创建 UI。我已经实现了这一点并创建了所需的控件。我根据分配给它们的标签来区分每个控件,这不是有效的方法。无论如何在动态创建 UIControl 时将名称(以下示例中的标签和文本字段除外)分配给它?
NSMutableArray *myArray = [[NSMutableArray alloc] initWithCapacity: myArrayCount];
for ( loop = 0; loop< myArrayCount; loop++ ) {
NSString *propertyName = [NSString stringWithFormat:@"Label %d", loop];
[myArray addObject:propertyName];
CGRect labelFrame = CGRectMake(xLabel, yLabel, widthLabel, heightLabel);
UILabel *label = [[UILabel alloc] initWithFrame: labelFrame];
label.tag = loop;
[label setText:propertyName];
[label sizeToFit];
[self.view addSubview:label];
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(xTextField, yTextField, widthTextField, heightTextField)];
textField.tag = loop;
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.font = [UIFont systemFontOfSize:15];
textField.placeholder = @"Enter parameter value";
textField.autocorrectionType = UITextAutocorrectionTypeNo;
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.returnKeyType = UIReturnKeyDone;
textField.delegate = self;
[self.view addSubview:textField];
yLabel = yLabel+yOffset;
yTextField = yTextField+yOffset;
}
【问题讨论】:
-
标签是识别动态 UIControls 的有效方法,如果你按名称去的话,它会让事情变得更复杂。
-
我想是这样,但只是想知道是否有人有其他解决方案。每次我想访问特定文本字段的值时,我都必须解析所有文本字段并获取具有正确标签的文本字段并获取它的值!此外,我还有许多其他控件,如按钮、分段控件、uipicker 等……我可以为所有这些控件使用标签吗?
标签: ipad ios5 dynamically-generated uicontrol