creating more than one label variable programmatically
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++)
{
开发者_Go百科 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];
}
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.
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;
}
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
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;
}
精彩评论