Reputation: 1289
How can I create more than one label variable programmatically I tried following code but I am unable to create, is there any way to concatenate a variable name and a integer?
for(int intNum=0;intNum<3;intNum++)
{
UILabel *lblText1;
UILabel *lblmany = [lblText1 stringByAppendingString:intNum];
lblmany = [[UILabel alloc] initWithFrame:CGRectMake(65, 50, 200, 30)];
lblmany.text = strLable1Caption;
lblmany.textAlignment = UITextAlignmentCenter;
[self.view addSubview:lblmany];
[lblText1 release];
[lblmany release];
}
Upvotes: 0
Views: 227
Reputation: 3754
I used this code to create buttons at different locations, you can use UILabels instead of buttons.
int x =15;
int y =12;
for (int i =0 ; i <numberamount; i++) {
if (x>273) {
x=15;
y=y+50;
}
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(x, y, 40, 40);
[button setTitle:[nmb objectAtIndex:i] forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed:)
forControlEvents:UIControlEventTouchUpInside];
NSString *tagindex = [[NSString alloc]initWithFormat:@"%@",[nmb objectAtIndex:i]];
int tagindexint = [tagindex intValue];
[button setTag:tagindexint];
[buttons addSubview:button];
[tagindex release];
x = x+75;
}
Upvotes: 0
Reputation: 10344
Try this,
myController.h
#defune MAX_LABELS 2048
@interface myController : UIViewController
{
UILabel *myLabels[MAX_LABELS];
NSInteger myLabelsCount;
}
- (void) createMyLabels;
- (void) removeMyLabels;
@end
myController.m
@implementation myController
- (void) createMyLabels
{
[self removeMyLabels];
float x = 10.0;
float y = 5.0;
myLabelsCount = 0;
for (int i = 0; i < [No of labels]; i++)
{
myLabels[myLabelsCount] = [[UILabel alloc] initWithFrame:CGRectMake(x, y, 200, 30)];
myLabels[myLabelsCount].text = strLable1Caption;
myLabels[myLabelsCount].textAlignment = UITextAlignmentCenter;
[self.view addSubview:myLabels[myLabelsCount]];
myLabelsCount++;
y = y + 15.0;
}
}
- (void) removeMyLabels
{
for (int i = 0; i < myLabelsCount; i++)
{
[jmyLabels[i] removeFromSuperview];
}
myLabelsCount = 0;
}
- (void)dealloc {
[super dealloc];
}
@end
Upvotes: 0
Reputation: 1838
you are creating label with same frame, how come it will be placed at different location ?? Define frame dynamically not with static values, And if you want to apply different properties use switch case if want to use for loop only ,else define separately and not in loop.
Upvotes: 1
Reputation: 12787
Your code is ridiculous (and stringByAppendingString is an istance method of NSString calss so you cant access it with UILabel). what are you trying to do if you want to create number of labels the do some thing like this.
for(int intNum=0;intNum<3;intNum++)
{
UILabel *lbl;
lbl = [[UILabel alloc] initWithFrame:CGRectMake(65, 50, 200, 30)];
lbl.text = strLable1Caption;
llbl.textAlignment = UITextAlignmentCenter;
[self.view addSubview:lbl];
[lbl release];
lbl=nil;
}
Upvotes: 0