views:

56

answers:

2

Hi,

I have a peace of code like this:

CGSize lSize = [@"Hello World" sizeWithFont:[UIFont fontWithName:@"Arial" size:13]];

Now I want to have the right frame to see this text in the UITextField. I don't want to change the font size just have the frame for UITextField to fit with this text.

I will really appreciate any helps

A: 
#define MAIN_FONT_SIZE      17
#define MIN_MAIN_FONT_SIZE  11
#define MAX_TEXT_WIDTH      100

CGPoint point;
CGFloat actualFontSize;
CGSize size;

UIFont *mainFont = [UIFont systemFontOfSize:MAIN_FONT_SIZE];

NSString *string = @"A String Of Text";
size = [string sizeWithFont:mainFont 
             minFontSize:MIN_MAIN_FONT_SIZE 
             actualFontSize:&actualFontSize 
             forWidth:MAX_TEXT_WIDTH 
             lineBreakMode:UILineBreakModeTailTruncation];

From here you can either adjust the width of your textField:

[textField setFrameSize:NSMakeSize(size.width,textField.frame.size.height)];

Or you can draw the text at a calculated point based on the size:

point = CGPointMake(textXPosition, textYPosition);
[string drawAtPoint:point 
              forWidth:MAX_TEXT_WIDTH 
              withFont:mainFont 
              minFontSize:actualFontSize actualFontSize:&actualFontSize 
              lineBreakMode:UILineBreakModeTailTruncation 
              baselineAdjustment:UIBaselineAdjustmentAlignBaselines];
Kenny
A: 

Thanks Kenny :)

JustMe