Showing posts with label UILabel. Show all posts
Showing posts with label UILabel. Show all posts

Sunday, June 17, 2012

Label with dynamic height

The below code creates the dynamic height to fit for the inputed text

-(void)createDynamicHeight
{
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 300, 40)];
label.backgroundColor = [UIColor blackColor];
[self.view addSubview:label];
NSString *text = @"This is label with dynamic height";
label.text = text;
label.lineBreakMode = UILineBreakModeWordWrap;
    
// resize the height to fit the content
CGSize newLabelSize = [text sizeWithFont:label.font 
                       constrainedToSize:label.frame.size
                           lineBreakMode:UILineBreakModeWordWrap];
    
CGRect newFrame = instructions.frame;

if (newLabelSize.height > 40) {
      newFrame.size.height = newLabelSize.height;
} else {
      newFrame.size.height = 40
}
label.frame = newFrame;
label.numberOfLines = 0;

NSLog(@"Label height is %f", label.frame.size.height);
}

Saturday, March 3, 2012

Set multi-lines in the label

Set the lines = 0 in the label tab, then the text can be shown as the multi-line in the UILabel. Actually it can be done in code too.

Saturday, December 17, 2011

Display the multi-lines in the UILabel

To use NSString method, "sizeWithFont:constrainedToSize: lineBreakMode:"
It figure out the UILabel size to accommodate the long String.




//  init the content of string

NSString *string = @"Cocos2d-x open source project is C++ version of cocos2d-iphone. We focus on making cocos2d framework cross multiple platforms. Mobile games can be written on the top of cocos2d-x in C++ or Lua language, via the COMPLETELY SAME API as cocos2d-iphone, they can easily be built & run on iOS, Android, Samsung Bada and BlackBerry Tablet OS. Cocos2d-x also supports Windows & Linux, therefore we can debug source code easily and write editors on desktop operating systems."; 

// Determine the size of UILabel for the string
CGSize aSize = [string sizeWithFont: [UIFont systemFontOfSize:18] constrainedToSize:CGSizeMake(250.0, 999.0) lineBreakMode:UILineBreakModeWordWrap]; 

 // Declare UILabel,
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(20, 20, aSize.width, aSize.height)]; 

 // init the label
label.backgroundColor = [UIColor grayColor]; 
label.textColor = [UIColor redColor]; 
label.font = UIFont systemFontOfSize:18;
label.lineBreakMode = UILineBreakModeWordWrap; 
label.text = string; 
label.numberOfLines = 0;  
[self.view addSubview:label];