I have trouble changing the text in a label programmatically.
When I run the following code, NSLog does display "Setting myLabel to = Hello World!", but the label on the screen is not changed.
UIViewOverlay *overlayWindow;
overlayWindow = [[[NSBundle mainBundle] loadNibNamed:@"UIViewOverlay" owner:self options:nil] objectAtIndex:0];
[self addSubview:overlayWindow];
[overlayWindow setMyLabel:@"Hello World!"];
My NIB file has a 300x300 window with some labels and buttons. There is a label, which is connected to myLabel in the outlet. The UIView does display, just that the text cannot be changed programmatically.
UIViewOverlay.h
#import <UIKit/UIKit.h>
@interface UIViewOverlay : UIView {
IBOutlet UILabel *myLabel;
}
- (void)setMyLabel:(NSString *) label;
@end
UIViewOverlay.m
#import "UIViewOverlay.h"
@implementation UIViewOverlay
- (void)setMyLabel:(NSString *) label {
myLabel.text = label; // THIS LINE IS NOT WORKING! :-(
NSLog(@"Setting myLabel to = %@", label); // This line is working.
}
@end
Thanks in advance..
You are using an incorrect accessor name for your method to set the label string.
In cocoa,
setFoo
is the method by which an instance variable calledfoo
is assigned. This isn't just a convention, many areas of functionality depend on it, for example the use of properties, key value coding etc.In your code, your label is called
myLabel
. Your method to set the text of that label is calledsetMyLabel
. Either this is causing your outlet to not be connected when the nib is loaded, as the runtime may be trying to use that method to assign the label to your instance variable in the first place, or all of the above has no effect and you have just not connected your outlet.