iOS:动态创建名称并为UIControl分配名称

时间:2012-06-28 09:42:38

标签: ipad ios5 dynamically-generated uicontrol

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

}

2 个答案:

答案 0 :(得分:0)

虽然您无法通过类别将iVar添加到UIControl,但您可以添加关联对象,这可以用来执行相同的功能。

因此,在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 Docs

答案 1 :(得分:0)

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

所以也许类似的东西(修改你的代码并省略了一些细节):

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"]

等语句检索控件