UITextField right frame

☆樱花仙子☆ 提交于 2019-12-10 12:05:42

问题


I have a piece 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 help


回答1:


#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];


来源:https://stackoverflow.com/questions/2979661/uitextfield-right-frame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!