Search code examples
iosobjective-clabeliboutlet

Input text from function into label text?


I have a function that, for simplicity, let's say gives me the day of the week (it does something else, but that's not important). I used NSLog to verify that the function does in fact give a value, but I can't for the life of me get the text to input and display on the label in the iOS simulator. The relevant code is:

-(void)displayLabel {
NSString *result=[self days];
NSLog(@"%@", result);
displayLabel.text=result;
}

I have also tried in place of displayLabel.text=result, stringWithFormat, but I think have been getting the syntax wrong:

displayLabel.text= [NSString stringWithFormat@"%@":result];

The label has an outlet as well as an action in my .h file that looks like this:

@interface ViewController : UIViewController
{
IBOutlet UILabel *displayLabel;
}
-(IBAction)displayLabel:(id)sender;

@end

Finally, the label itself was placed and kept blank on the view controller in the storyboard. I'm not sure if that has any effect.

So, what am I doing wrong? Can I only display literals? Is my syntax off? What is the correct way of getting the text to display?


Solution

  • I am not sure why you insist on using the same name for the method and the name of the label, it is always a good practice to name them differently to avoid confusion when troubleshooting for errors later. Test this:

    In .h

    @interface ViewController : UIViewController
    @property (weak, nonatomic) IBOutlet UILabel *displayLabel;
    @end
    

    Create IBOutlet for displaying text in the UILabel and changing its properties. Create IBAction only if you need to interact with the UI and perform certain functions (however, very seldom used on UILabels).

    In .m

    - (void)showDisplayLabel 
    {
        NSString *result=[self days];
        NSLog(@"%@", result);
        self.displayLabel.text=result;
    }