Search code examples
iosobjective-cuilabelsizetofit

Create UILabel programmatically and set its position


I want to create a UILabel programmatically from a button click and set its position to the x,y coordinates: (50,50).

The text size can vary between 300 characters to 2,000 characters so I'm using:

[myLabel sizeToFit] 

to set the width and height of the label.

This is my code so far:

- (IBAction)createLabel:(id)sender {  //create label on button click

    UILabel *label;

    [label sizeToFit]; //set width and height of label based on text size

    //position label
    CGRect frame = label.frame;
    frame.origin = CGPointMake(50, 50);
    label.frame = frame;

    label.numberOfLines = 0;
    label.lineBreakMode = NSLineBreakByCharWrapping;
    label.text = @"This is where the text goes";

    [self.view addSubview:label];     //add label to view
}

It doesn't give me any errors when I run the program, but when I press the button to create a label, nothing shows up.


Solution

  • You're not actually creating a label.

    UILabel *label;
    

    Just declares a variable, you never initialise it or assign a value to it. You either need a reference to an existing label or you need to create one using initWithFrame:

    Also, sizeToFit should be done after you've assigned the text.