objective c查找字符串的像素宽度

Ama*_*rsh 1 size fonts pixel objective-c

替代文字

我有一个固定宽度的UIButton,我想在其中放置文本.由于String的大小事先是未知的,因此当我从平面文件中读取String时,我将不得不调整字体大小.我怎样才能做到这一点?类似于以下的功能将很棒:

UIFont resizeFontAs:(UIFont)initialFont andStringAs:(NSString*)string andWidthAs:(int)width
Run Code Online (Sandbox Code Playgroud)

提前致谢

编辑:此代码似乎不起作用:

// Method for creating button, with background image and other properties
- (UIButton *) getCallAgentButtonWithTitleAs:(NSString *)aTitle andImageAs:(UIImage*)bgImg atIndex:(int)index{    
    UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];  
    aButton.frame = CGRectMake(10, 2+index*50, 300, 48);    
    aButton.titleLabel.frame = CGRectMake(aButton.titleLabel.frame.origin.x + 25.0,                   aButton.titleLabel.frame.origin.y, aButton.titleLabel.frame.size.width - 50.0,     aButton.titleLabel.frame.size.height);     
    aButton.titleLabel.adjustsFontSizeToFitWidth = YES;
    [aButton setTitle:aTitle forState:UIControlStateNormal];
    //aButton.titleLabel.font = [UIFont boldSystemFontOfSize:12];   
    [aButton setTitleColor:UIColorFromRGB(0xFDD428) forState:UIControlStateNormal];
    [aButton setBackgroundImage:bgImg forState:UIControlStateNormal];
    [aButton addTarget:self action:@selector(callAgent:) forControlEvents:UIControlEventTouchUpInside];
    // set the tag as the index and use it later to obtain the phoneNo
    [aButton setTag:index];
    return aButton;  
}
Run Code Online (Sandbox Code Playgroud)

Kri*_*kel 5

您可以告诉按钮的标签来调整字体本身的大小.

myButton.titleLabel.adjustsFontSizeToFitWidth = YES;
myButton.titleLabel.minimumFontSize = 6.0; // Pick your own value here.
Run Code Online (Sandbox Code Playgroud)