0

我正在尝试编写数据驱动应用程序,在其中解析 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;

}
4

2 回答 2

0

虽然您无法UIControl通过类别添加 iVar,但您可以添加Associated Objects,它可用于执行几乎相同的功能。

所以,UIControl像这样创建一个类别:

static char kControlNameKey;

- (void) setControlName: (NSString *) name
{
    objc_setAssociatedObject(self, &kControlNameKey, name, OBJC_ASSOCIATION_COPY);
}

- (NSString *) controlName
{
    return (NSString *)objc_getAssociatedObject(array, &kControlNameKey);
}

不仅如此,我想您需要在设置新关联之前检查关联是否存在,否则它会泄漏,但这应该给您一个开始。

有关更多详细信息,请参阅Apple 文档

于 2012-06-28T09:57:13.707 回答
0

假设您不想[self.view viewWithTag:tag]用来检索控件,通过名称引用动态创建的控件的一种方法是将其放入NSMutableDictionary带有动态生成的键的控件中。

所以也许是这样的(修改你的代码,省略了一些细节):

NSMutableDictionary *controlsDictionary = [[NSMutableDictionary alloc] init];
for ( loop = 0;  loop< myArrayCount; loop++ ) {

CGRect labelFrame = CGRectMake(xLabel, yLabel, widthLabel, heightLabel);
UILabel *label = [[UILabel alloc] initWithFrame: labelFrame];
[controlsDictionary setObject:label forKey:[NSString stringWithFormat:@"label%d", loop]];

UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(xTextField, yTextField, widthTextField, heightTextField)];
[controlsDictionary setObject:label forKey:[NSString stringWithFormat:@"textField%d", loop]];

yLabel = yLabel+yOffset; 
yTextField = yTextField+yOffset;

}

然后您可以通过以下语句检索控件[controlsDictionary objectForKey:@"label1"]

于 2012-07-06T09:47:47.497 回答