I am trying to write data drive App where I parse json string to create UI. I have implemented this and created required controls. I am differentiating each control based on the tag assigned to them which is not efficient way. Is there anyway to assign name(other than label and textfield in following example) to UIControl while creating it dynamically?
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;
}
Assuming you don’t want to use
[self.view viewWithTag:tag]to retrieve your controls, one way to reference a dynamically created control by name would be to put it in anNSMutableDictionarywith a dynamically generated key.So maybe something like (a modification of your code with some of the details elided):
Then you can retrieve the controls via statements like
[controlsDictionary objectForKey:@"label1"]