开发者

Writing UILabels in viewdidload Objective-C

Want i want to do is i get a number from a php script. This number determines the labels that have to be added to the view. The php script is very simple and is the following:

<?php

echo (int)5;

?>

The objc script has to determine the number and needs to write as many labels als the php script describes. I am showing the string in another label to be sure that the number is being returned. How do i write those labels to my view?

I got some code as follows:

- (void)viewDidLoad
{
    NSString *post = @"";
    NSData *postData = [post dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:NO];
    NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc] init] autorel开发者_高级运维ease];
    [urlRequest setURL:[NSURL URLWithString:@"http://......./testGet.php"]];
    [urlRequest setHTTPMethod:@"POST"]; 
    [urlRequest setHTTPBody:postData];


    NSData *urlData; 
    NSURLResponse *response; 
    NSError *error;
    urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error]; 
    if(!urlData) {
        NSLog(@"No connection!");
    }

    NSString *aStr = [[[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding]autorelease]; 


    int i;
    i = [aStr intValue];
    status.text = [NSString stringWithFormat:@"%d",i];

    for (int i; i <= 10; i++)
    {

        UILabel *mijnlabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];

        mijnlabel.text = @"Loremipsum";
        [self.view addSubview:mijnlabel];
    }

    [super viewDidLoad];
}


Although your labels will all display at the same position, you are right to do so by sending [self.view addSubview:mijnlabel]; to the view.

You have to be careful on these few things :

  1. The way you right your loop, use as the counter, another variable rather than the value you parsed from the string.
  2. Don't forget to release the UILabelyou initialized just after adding it to the view.
  3. Send viewDidLoad first to the super view.

So your might result to :

// first
[super viewDidLoad];

...

NSString *aStr = [[[NSString alloc]
                   initWithData:urlData
                       encoding:NSUTF8StringEncoding]autorelease]; 
int labelsCount = [aStr intValue];
status.text = [NSString stringWithFormat:@"%d",labelsCounts];
// another way, in order to display the label under each other
// this will display labelsCount labels
int i;
for(i = 0; i < labelsCount; i++) {
    CGFloat yCoord = i * 100;
    UILabel *mijnlabel = [[UILabel alloc]
                          initWithFrame:CGRectMake(50, yCoord, 200, 100)];
    mijnlabel.text = @"Loremipsum";
    [self.view addSubview:mijnlabel];
    [mijnLabel release];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜