-
Notifications
You must be signed in to change notification settings - Fork 1
AA 1.17. Displaying Static Text with UILabel
To create a label, instantiate an object of type UILabel. Setting or getting the text of a label can be done through its text property. So let’s first define a label in our view controller’s implementation file:
#import "ViewController.h" @interface ViewController () @property (nonatomic, strong) UILabel *myLabel; @end
Now in the viewDidLoad method, instantiate the label and tell the runtime where the label has to be positioned (through its frame property) on the view to which it will be added (in this case, our view controller’s view):
- (void)viewDidLoad { [super viewDidLoad]; CGRect labelFrame = CGRectMake(0.0f, 0.0f, 100.0f, 40.0f); self.myLabel = [[UILabel alloc] initWithFrame:labelFrame]; self.myLabel.text = @"iOS 7 Programming Cookbookkk"; self.myLabel.font = [UIFont boldSystemFontOfSize:14.0f]; self.myLabel.center = self.view.center; [self.view addSubview:self.myLabel]; }
You can see that the contents of the label are truncated, with a trailing ellipsis, because the width of the label isn’t enough to contain the whole contents. One solution would be to make the width longer, but how about the height? What if we wanted the text to wrap to the next line? OK, go ahead and change the height from 23.0f to 50.0f:
[super viewDidLoad]; CGRect labelFrame = CGRectMake(0.0f, 0.0f, 100.0f, 40.0f); self.myLabel = [[UILabel alloc] initWithFrame:labelFrame]; self.myLabel.text = @"iOS 7 Programming Cookbookkk"; self.myLabel.font = [UIFont boldSystemFontOfSize:14.0f]; self.myLabel.center = self.view.center; [self.view addSubview:self.myLabel]; self.myLabel.numberOfLines = 3; //self.myLabel.lineBreakMode = NSLineBreakByCharWrapping; self.myLabel.adjustsFontSizeToFitWidth = YES; self.myLabel.shadowColor = [UIColor redColor]; self.myLabel.shadowOffset = CGSizeMake(2.0f, 2.0f); self.myLabel.textColor = [UIColor blackColor]; self.myLabel.shadowColor = [UIColor lightGrayColor]; self.myLabel.shadowOffset = CGSizeMake(2.0f, 2.0f); [self.myLabel sizeToFit];