Monday, September 10, 2012

Create UILabel in iphone exam

While developing my first iPhone game App, I’m finding Interface Builder very easy to use. However, in my coding, I had the need to add a UILabel programatically. Similar to other languages/platforms I’ve worked with, handling font size, color and weight can be a little confusing.
The code below shows how to:
- Create new UILabel
- Set UILabel position (x,y) to center and size
- Set UILabel font alignment, color, font name and size
- Add UILabel to your View
- Populate UILabel with an NSString for text.

UILabel *scoreLabel = [ [UILabel alloc ] initWithFrame:CGRectMake((self.bounds.size.width / 2), 0.0, 150.0, 43.0) ];
scoreLabel.textAlignment =  UITextAlignmentCenter;
scoreLabel.textColor = [UIColor whiteColor];
scoreLabel.backgroundColor = [UIColor blackColor];
scoreLabel.font = [UIFont fontWithName:@"Arial Rounded MT Bold" size:(36.0)];
[self addSubview:scoreLabel];
scoreLabel.text = [NSString stringWithFormat: @"%d", score];
 
The score value being set is an int that I’m incrementing based on CGRectIntersectsRect of two UIImageViews. I’ll post that example soon.
If you’ve got a better, more efficient way of doing the above, please feel free to comment.

No comments:

Post a Comment