Question

I currently run a function on a button click. This is my .m, and everything to this point is working fine.

- (IBAction)buttonReact:(id)sender
{
    NSLog(@"clicked");
}

However, how can allow this function to dynamically create a label with specific text and at a specific coordinate?

For instance, the text could be "clicked" and coordinate at (10, 10) on the screen. Nevertheless, this code always runs on a button click, so I want it to be able to add multiple labels as well. Meaning, multiple labels can be on the screen, depending on when the button was clicked/how fast it was clicked.

Was it helpful?

Solution

Here is how to do it:

- (IBAction)buttonReact:(id)sender
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100.0f, 
                                                               100.0f,
                                                               100.0f,
                                                               40.0f)];
    label.text = @"Your text";
    [self.view addSubview:label];
}

Or you can even go crazy and add the label at random location on the screen:

- (IBAction)buttonReact:(id)sender
{    
    CGPoint randomLocation = CGPointMake(arc4random_uniform(CGRectGetWidth(self.view.bounds)),
                                         arc4random_uniform(CGRectGetHeight(self.view.bounds)));

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(randomLocation.x,
                                                               randomLocation.y,
                                                               100.0f,
                                                               40.0f)];
    label.text = @"Your text";    
    [self.view addSubview:label];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top